OPTIONS

Insert Documents

In MongoDB, the db.collection.insert() method adds new documents into a collection. In addition, both the db.collection.update() method and the db.collection.save() method can also add new documents through an operation called an upsert. An upsert is an operation that performs either an update of an existing document or an insert of a new document if the document to modify does not exist.

This tutorial provides examples of insert operations using each of the three methods in the mongo shell.

Insert a Document with insert() Method

The following statement inserts a document with three fields into the collection inventory:

db.inventory.insert( { _id: 10, type: "misc", item: "card", qty: 15 } )

In the example, the document has a user-specified _id field value of 10. The value must be unique within the inventory collection.

For more examples, see insert().

Insert a Document with update() Method

Call the update() method with the upsert flag to create a new document if no document matches the update’s query criteria. [1]

The following example creates a new document if no document in the inventory collection contains { type: "books", item : "journal" }:

db.inventory.update(
                     { type: "book", item : "journal" },
                     { $set : { qty: 10 } },
                     { upsert : true }
                   )

MongoDB adds the _id field and assigns as its value a unique ObjectId. The new document includes the item and type fields from the <query> criteria and the qty field from the <update> parameter.

{ "_id" : ObjectId("51e8636953dbe31d5f34a38a"), "item" : "journal", "qty" : 10, "type" : "book" }

For more examples, see update().

[1]Prior to version 2.2, in the mongo shell, you would specify the upsert and the multi options in the update() method as positional boolean options. See update() for details.

Insert a Document with save() Method

To insert a document with the save() method, pass the method a document that does not contain the _id field or a document that contains an _id field that does not exist in the collection.

The following example creates a new document in the inventory collection:

db.inventory.save( { type: "book", item: "notebook", qty: 40 } )

MongoDB adds the _id field and assigns as its value a unique ObjectId.

{ "_id" : ObjectId("51e866e48737f72b32ae4fbc"), "type" : "book", "item" : "notebook", "qty" : 40 }

For more examples, see save().