MongoDB Create Document

MongoDB provides insert() method to create a new document or insert documents to a collection. If the collection does not already exist, then the insert() method creates the collection and inserts a document in it.

Syntax of Insert Document

db.COLLECTION_NAME.insert(
	<document>,
	{
		writeConcern: <document>,
		ordered: <boolean>
	}
)

The insert() method accepts the following parameters-

Parameter Type Description
document document/ array A single document or documents array to insert into a collection.
writeConcern document It is an optional parameter. It overlooks the need to utilize the default write concern.
ordered boolean It is an optional parameter. If it is set to true, perform an ordered insertion of the document and if it is set to false, perform an unordered insertion of a document.




The insert categories in three categories -

  • insert()
  • insertOne()
  • insertMany()

MongoDB insert() Method

The MongoDB insert() method is used to insert one or more documents into a collection. MongoDB accepts documents in JSON format and in JSON, data represented as key-value pairs and enclosed within curly braces {}.

Example of insert()

> db.students.insert({name:"Zorj Roi", age: 10, class: '5A'});
WriteResult({ "nInserted" : 1 })

Here, 'students' is the collection name. It contains three key and value pairs for storing student data.

The WriteResult returns result status of the insert statement. The nInserted contains number of inserted documents. As in the above example, it has inserted one document.

Let's check how it has inserted document in database-

> db.students.find().pretty();
{
        "_id" : ObjectId("5d44ec8c4e7b51c3f3698346"),
        "name" : "Zorj Roi",
        "age" : 10,
        "class" : "5A"
}

As you can see, the _id is inserted automatically. All documents require a primary key stored in the _id field. If we do not provide the _id parameter, then MongoDB automatic assigns unique Object Id to each inserted document.
Here, we have custom generated _id in document insertion using ObjectId() method.

> db.students.insert({"_id": ObjectId("5d44ec8c4e7b51c3f3698346"), "name": "Priska", "age": 11, "class": "6A"});
WriteResult({ "nInserted" : 1 })

MongoDB insertOne() Method

The MongoDB insertOne() method is used to insert only one document into a collection. The following example inserts a new document into the students collection.

Example

db.students.insertOne({name: "Rana Soi", age: 11, class: '6B'})

MongoDB insertMany() Method

The MongoDB insertMany() method is used to insert multiple documents into a collection. We can pass an array of documents into a collection.

Example

db.students.insertMany(
[
{name: "Andy Joya", age: 10, class: '5A'},
{name: "Mary Soi", age: 11, class: '5B'},
{name: "Priska Somya", age: 12, class: '6A'}
]
)

In insertMany(), each document is enclosed in curly braces and separated by a comma. It returns a true acknowledgement with Object Ids on success.

{
        "acknowledged" : true,
        "insertedIds" : [
                ObjectId("5d3ede3bc242c2522305fb4b"),
                ObjectId("5d3ede3bc242c2522305fb4c"),
                ObjectId("5d3ede3bc242c2522305fb4d")
        ]
}




Insert Large Documents in a Collection

As we know, the MongoDB shell is also a Javascript interpreter. So, we can use Javascript code in the MongoDB shell. Suppose we have to insert numbers from 1 to 50 in a 'Numbers' collection. We can write the code as -

> for(i=1; i<=50; i++){
... db.numbers.save({num: i});
... }
WriteResult({ "nInserted" : 1 })
> db.numbers.count();
50

Show Errors

If you want to show reported errors, if any, write the following command. It returns null for no error and error string otherwise.

db.getLastError()

Difference Between insert() and save()

Both insert() and save() are used to insert the document. The difference with saving is that if we pass a document containing an _id field and that _id already exists with a document, then it will be updated instead of inserting a new one.







Read more articles


General Knowledge



Learn Popular Language