In MongoDB, inserting documents into a collection is done using the insertOne
and insertMany
methods. These methods allow you to add one or more documents to a collection, respectively.
db.collection.insertOne(document)
db.collection.insertMany([document1, document2, ...])
The insertOne
method inserts a single document, while the insertMany
method inserts multiple documents at once.
Let's look at some examples of how to insert documents into a collection in MongoDB:
db.programGuru.insertOne({ name: "John Doe", age: 30, email: "john.doe@example.com" })
This command inserts a single document into the programGuru
collection.
db.programGuru.insertMany([
{ name: "Jane Smith", age: 25, email: "jane.smith@example.com" },
{ name: "Jim Brown", age: 35, email: "jim.brown@example.com" }
])
This command inserts multiple documents into the programGuru
collection.
Let's go through a complete example that includes switching to a database, creating a collection, inserting documents, and verifying the insertions.
This step involves switching to a database named myDatabase
.
use myDatabase
In this example, we switch to the myDatabase
database.
This step involves creating a new collection named programGuru
in the myDatabase
database.
db.createCollection("programGuru")
Here, we create a collection named programGuru
.
This step involves inserting documents into the programGuru
collection.
db.programGuru.insertOne({ name: "John Doe", age: 30, email: "john.doe@example.com" })
We insert a single document into the programGuru
collection.
db.programGuru.insertMany([
{ name: "Jane Smith", age: 25, email: "jane.smith@example.com" },
{ name: "Jim Brown", age: 35, email: "jim.brown@example.com" }
])
We insert multiple documents into the programGuru
collection.
This step involves querying the programGuru
collection to verify that the documents have been inserted.
db.programGuru.find().pretty()
This command retrieves all documents from the programGuru
collection and displays them in a readable format.
The MongoDB insert document
operation is essential for adding data to collections. Understanding how to insert single and multiple documents allows you to effectively manage your data in MongoDB.