MongoDB Create Document (CRUD) Tutorial
In this MongoDB tutorial we learn the first CRUD operation, creating documents.
We cover how to create single documents as well as how to create multiple documents at once.
How to create (insert) new documents
If we want to create new documents and add them to a collection, we use the db.collection.insert() method.
This method takes one argument.
- document to specify the data to be inserted
db.collection_name.insert(document)
The terminal/command prompt will allow you to write the data on separate lines by pressing Enter after each line. Once the function’s parameter list is closed with the closing bracket, pressing Enter will run the command.
db.posts.insert({
"title": "How to Mongo",
"description": "Learn how to Mongo",
"author": "John Doe",
"url": "/how-to-mongo/",
"tags": ["MongoDB", "Database", "Learn"],
"likes": 10,
"rating": [{ "score": 6 }, { "score": 7 }],
"comments":
[{
"user": "Jane",
"comment": "Thanks for the toot",
"timestamp":"2020-11-09",
"likes": 4
},
{
"user": "Jack",
"comment": "You forgot DB at the end",
"timestamp":"2020-11-10",
"likes": 3
}]
})
If the operation succeeded, the terminal will return with an affirmative message indicating how many documents were created.
WriteResult({ "nInserted" : 1 })
Alternatively, we can use the db.collection.insertOne() function in the exact same way if we only need to create a single document in a collection.
How to create multiple new documents at once
We can create multiple new documents at once by passing an array as argument for the db.collection.insert() method.
db.users.insert([
{
"name": "John",
"email": "john@example.com"
},
{
"name": "Jane",
"email": "jane@example.com"
}
])
The terminal will return the statistics of the operation.
BulkWriteResult({
"writeErrors" : [ ],
"writeConcernErrors" : [ ],
"nInserted" : 2,
"nUpserted" : 0,
"nMatched" : 0,
"nModified" : 0,
"nRemoved" : 0,
"upserted" : [ ]
})
In this case both users were added to the document so the nInserted field shows 2.
Alternatively, we can use the db.collection.insertMany() function in the exact same way.