Inserting
Lesson 5Author : Afrixi
Last Updated : February, 2023
To insert data into a MongoDB collection, you can use the insertOne()
or insertMany()
method depending on whether you want to insert a single document or multiple documents.
Here is an example of using insertOne()
to insert a single document into a collection named users
:
db.users.insertOne({
name: "John",
age: 30,
email: "john@example.com"
})
This will insert a document with the specified fields and values into the users
collection.
If you want to insert multiple documents, you can use insertMany()
method. Here is an example:
db.users.insertMany([
{
name: "John",
age: 30,
email: "john@example.com"
},
{
name: "Jane",
age: 25,
email: "jane@example.com"
},
{
name: "Bob",
age: 40,
email: "bob@example.com"
}
])
This will insert three documents into the users
collection.
Note that MongoDB will automatically generate an _id
field for each document if you don’t provide one. The _id
field is a unique identifier for the document.