MongoDB Insert Documents

MongoDB Insert Documents: Insert operations create a collection if it does not exist currently. There are three methods to insert documents into a MongoDB database.

  • insert()
  • insertOne()
  • insertMany()
  • Insert() method:

This method is used to insert one or more documents in the collection. Each document is given as a parameter to the method.

Inserting a single document:

 Syntax:

db.collectionName.insert({name: "value"})

Since MongoDB uses JSON format documents, so the document has{name,"value"}.

Example

db.books.insert({authorname:"Chitra Divakaruni"})

The above example inserts a document with content {authorname:"Chitra Divakaruni"}

To see the documents of the collection, use the command:

db.collection.find()

If you do not specify any –id, the MongoDB creates it automatically.

Example:

> use booksdb
 switched to db booksdb
 > db.books.insert({authorname: "Chitra Divakaruni"})
 WriteResult({ "nInserted" : 1 })
 > db.books.find()
 { "_id" : ObjectId("5ded3592e96690a9c945a59d"), "authorname" : "Chitra Divakarun
 i" } 

Parameters of insert()

Parameter Type Description
document Document/array It can be either a document or an array of documents to be inserted into the collection.
writeconcern Document Acknowledgment is needed for write operations to a replica set, shards, or standalone mongodb. This optional parameter is a document describing the level of acknowledgment of write concern.
ordered Boolean This is an optional parameter. If its value is set to true, the documents are inserted into a sorted array, and if any of the documents contain an error, the remaining documents in the array will also not be processed. If the set value is false, then an unordered insert operation is performed. Even if an error occurs in a document, remaining documents are processed without fail.

Inserting multiple documents

Multiple documents are inserted in the form of an array. Here, documents are enclosed within [] and are separated by commas. The array name is passed to the insert method as:

Syntax:

db.collectionName.insert(arrayName);

This way of inserting multiple documents is called Bulk insert.

> var employee=
 ... [
 ... {
 ... Department: "MCA",
 ... details: { Name: "Akkash Deep", Designation: "Assistant Professor"},
 ... Profile: {Experience: 15, Area: "Network"},
 ... Type:"Regular Faculty"
 ... }, 
 ... {
 ... Department: "IT",
 ... details: {Name: "Anita", Desigination: "Associate Professor"},
 ... Profile: {Experience: 25, Area: "Testing"},
 ... Type:" Regular Faculty"
 ... }
 ... ]; 
 > db.institute.insert (employee);
 BulkWriteResult({
         "writeErrors" : [ ],
         "writeConcernErrors" : [ ],
         "nInserted" : 2,
         "nUpserted" : 0, 
         "nMatched" : 0,
         "nModified" : 0,
         "nRemoved" : 0,
         "upserted" : [ ]
 }) 

Inserting multiple documents with Bulk

MongoDB(latest version) provides an API that can perform the multiple write operations together in bulk.

  1. First of all, you have to initialize a bulk operation builder for a specific collection. The list of operations to be performed is maintained by an unorder operations builder returned by the bulk operation.
  2. Now add insert operations to he bulk object.
  3. Finally, execute the bulk operation by calling the execute method on the bulk object.
Inserting multiple documents with Bulk
  1. insertOne() method:

To insert a single document into the collection, insertOne() method is also used. The specified collection gets created if it does not exist in the database.

The output is quite different from the insert() method.

> use booksdb
 switched to db booksdb
 > var author=db.books.insertOne({“authorname”: "Chetan Bhagat"})
 > author
 {
  "acknowledged" : true,
  "insertedId" : ObjectId("5aed3592e96690a9c945a60de")
 } 
  1. insertMany() method:

You can also use insertMany() method for inserting multiple documents like insert(). It helps in inserting an array of documents. Here also, the output is quite different from insert().

> var books1 = db.books.insertMany([“Novel”: 20}, {'Magazine': 10}])
 > books1
 {
  "acknowledged" : true, 
  "insertedIds" : [
  ObjectId("671a22a911b82a1d94c01347"),
  ObjectId("671a22a911b82a1d94c01348")
  ] 
 } 

Note: Simple insert () method gives only the information of the number of documents inserted in the output, whereas insertOne() and insertMany() gives the object ids too.



ADVERTISEMENT
ADVERTISEMENT