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 document using the insert() method. It’s required a JSON format of the document to pass as arguments.

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

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

Insert Multiple Documents

To insert multiple documents in a 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": "jack@tecadmin.net",
	  "designation": "Director",
	  "location": "California"
	},
	{
	  "id": 1003,
	  "user_name": "peter",
	  "name": [
		    {"first_name": "Peter"},
		    {"middle_name": "S"},
		    {"last_name": "Jaction"}
	  ],
	  "email": "peter@tecadmin.net",
	  "designation": "Director",
	  "location": "California"
	}
];

Now pass the array as an 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" : [ ]
})
Reactions

Post a Comment

0 Comments

close