Insert Documents - (CRUD Operations)
In MongoDB, "Insert Document" is a CRUD (Create, Read, Update, Delete) operation used to insert a new document in a collection. In this page, we will discuss how to insert documents in MongoDB.
Syntax
The syntax for inserting a document in MongoDB is as follows:
db.collection.insertOne({"key": "value"})
Here, collection
refers to the collection name, and insertOne
is the method used to insert one document. You can also use the insertMany
method to insert many documents at once.
Example
Consider the following example where we will insert a document into an existing "users" collection:
> db.users.insertOne(
{
"name": "John Doe",
"email": "johndoe@example.com",
"phone": "123456789",
})
Output
After executing the above command, MongoDB will insert the document into the "users" collection and return the following output:
{
"acknowledged": true,
"insertedId": ObjectId("5f9a7035b3a2ce18312f850d")
}
The acknowledged
field is set to true if the write operation was successful, and the insertedId
field shows the unique ID of the inserted document.
Explanation
In the above example, we inserted a new document in the "users" collection with three fields: name
, email
, and phone
. MongoDB automatically adds a unique ID to each document in the _id
field.
Use
The "Insert Document" operation is used to add a new document to an existing collection in MongoDB. You can use this operation to add any type of data to your MongoDB collections.
Important Points
- To insert a document in MongoDB, you can use the
insertOne
orinsertMany
method. - The inserted document is automatically assigned a unique ID by MongoDB.
- You can insert any type of data in a MongoDB document.
Summary
In this page, we discussed how to insert documents in MongoDB. We covered the syntax, example, output, explanation, use, and important points of the "Insert Document" operation. By using this operation, you can easily add new data to your MongoDB collections.