How to create a new document in MongoDB

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": "A",
    "name": [
        {"first_name": "A"},
        {"middle_name": ""},
        {"last_name": "D"}
    ],
    "email": "[email protected]",
    "designation": "Some Guy",
    "location": "Global"
})
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": "Worker",
	  "location": "US"
	},
	{
	  "id": 1003,
	  "user_name": "Mark",
	  "name": [
		    {"first_name": "Mark"},
		    {"middle_name": "S"},
		    {"last_name": "Henry"}
	  ],
	  "email": "[email protected]",
	  "designation": "DBA",
	  "location": "US"
	}
];
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" : [ ]
})


Leave a comment or a question in the comment area bellow if you fell like


Be a sport and

Search

Loading... Please wait

Subscribe to our Newsletter

Be a sport and

x