1. Home
  2. MongoDB
  3. MongoDB Tutorial
  4. MongoDB – Insert Document

MongoDB – Insert Document

MongoDB Insert Document

Use db.collection.insert() method to insert new document to MongoDB collection. You don’t need to create the collection first. Insert method will automatically create collection if not exists.

Syntax

> db.COLLECTION_NAME.insert(document)  

Insert Single Document

Insert single ducument using the insert() method. It’s required a json format of document to pass as arguments.

> db.users.insert({
    "id": 1001,
    "user_name": "rahul",
    "name": [
        {"first_name": "Rahul"},
        {"middle_name": ""},
        {"last_name": "Kumar"}
    ],
    "email": "[email protected]",
    "designation": "Founder and CEO",
    "location": "India"
})

Output: WriteResult({ “nInserted” : 1 })

Insert Multiple Documents

To insert multiple documents in single command. The best way to create an array of documents like following:

> var users = 
  [
    {
	  "id": 1002,
	  "user_name": "jack",
	  "name": [
		    {"first_name": "Jack"},
		    {"middle_name": ""},
		    {"last_name": "Daniel"}
	  ],
	  "email": "[email protected]",
	  "designation": "Director",
	  "location": "California"
	},
	{
	  "id": 1003,
	  "user_name": "peter",
	  "name": [
		    {"first_name": "Peter"},
		    {"middle_name": "S"},
		    {"last_name": "Jaction"}
	  ],
	  "email": "[email protected]",
	  "designation": "Director",
	  "location": "California"
	}
];

Now pass the array as argument to insert() method to insert all documents.

> db.users.insert(users);

Output:

BulkWriteResult({
        "writeErrors" : [ ],
        "writeConcernErrors" : [ ],
        "nInserted" : 2,
        "nUpserted" : 0,
        "nMatched" : 0,
        "nModified" : 0,
        "nRemoved" : 0,
        "upserted" : [ ]
})
Tags , ,