MongoDB

MongoDB support

TypeORM has basic MongoDB support.Most of TypeORM functionality is RDBMS-specific,this page contains all MongoDB-specific functionality documentation.

Defining entities and columns

Defining entities and columns is almost the same as in relational databases,the main difference is that you must use @ObjectIdColumninstead of @PrimaryColumn or @PrimaryGeneratedColumn.

Simple entity example:

  1. import {Entity, ObjectID, ObjectIdColumn, Column} from "typeorm";
  2. @Entity()
  3. export class User {
  4. @ObjectIdColumn()
  5. id: ObjectID;
  6. @Column()
  7. firstName: string;
  8. @Column()
  9. lastName: string;
  10. }

And this is how you bootstrap the app:

  1. import {createConnection, Connection} from "typeorm";
  2. const connection: Connection = await createConnection({
  3. type: "mongodb",
  4. host: "localhost",
  5. port: 27017,
  6. database: "test"
  7. });

Defining subdocuments (embed documents)

Since MongoDB stores objects and objects inside objects (or documents inside documents)you can do the same in TypeORM:

  1. import {Entity, ObjectID, ObjectIdColumn, Column} from "typeorm";
  2. export class Profile {
  3. @Column()
  4. about: string;
  5. @Column()
  6. education: string;
  7. @Column()
  8. career: string;
  9. }
  1. import {Entity, ObjectID, ObjectIdColumn, Column} from "typeorm";
  2. export class Photo {
  3. @Column()
  4. url: string;
  5. @Column()
  6. description: string;
  7. @Column()
  8. size: number;
  9. constructor(url: string, description: string, size: number) {
  10. this.url = url;
  11. this.description = description;
  12. this.size = size;
  13. }
  14. }
  1. import {Entity, ObjectID, ObjectIdColumn, Column} from "typeorm";
  2. @Entity()
  3. export class User {
  4. @ObjectIdColumn()
  5. id: ObjectID;
  6. @Column()
  7. firstName: string;
  8. @Column()
  9. lastName: string;
  10. @Column(type => Profile)
  11. profile: Profile;
  12. @Column(type => Photo)
  13. photos: Photo[];
  14. }

If you save this entity:

  1. import {getMongoManager} from "typeorm";
  2. const user = new User();
  3. user.firstName = "Timber";
  4. user.lastName = "Saw";
  5. user.profile = new Profile();
  6. user.profile.about = "About Trees and Me";
  7. user.profile.education = "Tree School";
  8. user.profile.career = "Lumberjack";
  9. user.photos = [
  10. new Photo("me-and-trees.jpg", "Me and Trees", 100),
  11. new Photo("me-and-chakram.jpg", "Me and Chakram", 200),
  12. ];
  13. const manager = getMongoManager();
  14. await manager.save(user);

Following document will be saved in the database:

  1. {
  2. "firstName": "Timber",
  3. "lastName": "Saw",
  4. "profile": {
  5. "about": "About Trees and Me",
  6. "education": "Tree School",
  7. "career": "Lumberjack"
  8. },
  9. "photos": [
  10. {
  11. "url": "me-and-trees.jpg",
  12. "description": "Me and Trees",
  13. "size": 100
  14. },
  15. {
  16. "url": "me-and-chakram.jpg",
  17. "description": "Me and Chakram",
  18. "size": 200
  19. }
  20. ]
  21. }

Using MongoEntityManager and MongoRepository

You can use the majority of methods inside the EntityManager (except for RDBMS-specific, like query and transaction).For example:

  1. import {getManager} from "typeorm";
  2. const manager = getManager(); // or connection.manager
  3. const timber = await manager.findOne(User, { firstName: "Timber", lastName: "Saw" });

For MongoDB there is also a separate MongoEntityManager which extends EntityManager.

  1. import {getMongoManager} from "typeorm";
  2. const manager = getMongoManager(); // or connection.mongoManager
  3. const timber = await manager.findOne(User, { firstName: "Timber", lastName: "Saw" });

Just like separate like MongoEntityManager there is a MongoRepository with extended Repository:

  1. import {getMongoRepository} from "typeorm";
  2. const userRepository = getMongoRepository(User); // or connection.getMongoManager
  3. const timber = await userRepository.findOne({ firstName: "Timber", lastName: "Saw" });

Both MongoEntityManager and MongoRepository contain lot of useful MongoDB-specific methods:

createCursor

Creates a cursor for a query that can be used to iterate over results from MongoDB.

createEntityCursor

Creates a cursor for a query that can be used to iterate over results from MongoDB.This returns a modified version of the cursor that transforms each result into Entity models.

aggregate

Execute an aggregation framework pipeline against the collection.

bulkWrite

Perform a bulkWrite operation without a fluent API.

count

Count number of matching documents in the db to a query.

createCollectionIndex

Creates an index on the db and collection.

createCollectionIndexes

Creates multiple indexes in the collection, this method is only supported in MongoDB 2.6 or higher.Earlier version of MongoDB will throw a command not supported error. Index specifications are defined at http://docs.mongodb.org/manual/reference/command/createIndexes/.

deleteMany

Delete multiple documents on MongoDB.

deleteOne

Delete a document on MongoDB.

distinct

The distinct command returns returns a list of distinct values for the given key across a collection.

dropCollectionIndex

Drops an index from this collection.

dropCollectionIndexes

Drops all indexes from the collection.

findOneAndDelete

Find a document and delete it in one atomic operation, requires a write lock for the duration of the operation.

findOneAndReplace

Find a document and replace it in one atomic operation, requires a write lock for the duration of the operation.

findOneAndUpdate

Find a document and update it in one atomic operation, requires a write lock for the duration of the operation.

geoHaystackSearch

Execute a geo search using a geo haystack index on a collection.

geoNear

Execute the geoNear command to search for items in the collection.

group

Run a group command across a collection.

collectionIndexes

Retrieve all the indexes on the collection.

collectionIndexExists

Retrieve if an index exists on the collection

collectionIndexInformation

Retrieves this collections index info.

initializeOrderedBulkOp

Initiate an In order bulk write operation, operations will be serially executed in the order they are added, creating a new operation for each switch in types.

initializeUnorderedBulkOp

Initiate a Out of order batch write operation. All operations will be buffered into insert/update/remove commands executed out of order.

insertMany

Inserts an array of documents into MongoDB.

insertOne

Inserts a single document into MongoDB.

isCapped

Returns if the collection is a capped collection.

listCollectionIndexes

Get the list of all indexes information for the collection.

mapReduce

Run Map Reduce across a collection. Be aware that the inline option for out will return an array of results not a collection.

parallelCollectionScan

Return N number of parallel cursors for a collection allowing parallel reading of entire collection. There are no ordering guarantees for returned results

reIndex

Reindex all indexes on the collection Warning: reIndex is a blocking operation (indexes are rebuilt in the foreground) and will be slow for large collections.

rename

Changes the name of an existing collection.

replaceOne

Replace a document on MongoDB.

stats

Get all the collection statistics.

updateMany

Updates multiple documents within the collection based on the filter.

updateOne

Updates a single document within the collection based on the filter.