Insert Documents

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.

The 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.

The update() Method – Call the update() method with the upsert flag to create a new document if no document matches the update’s query criteria. 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” }

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.

The 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:

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

Apply for MongoDB Certification Now!!

https://www.vskills.in/certification/databases/mongodb-server-administrator

Back to Tutorial

Introduction
Read Operations

Get industry recognized certification – Contact us

keyboard_arrow_up
Open chat
Need help?
Hello 👋
Can we help you?