MongoDB Insert Many Documents
MongoDB Insert Many Documents
In MongoDB, the insertMany
operation is used to insert multiple documents into a collection in one go. This method is essential for bulk inserting records into MongoDB collections.
Syntax
db.collection.insertMany(documents, options)
The insertMany
method takes an array of documents
to specify the documents to be inserted and an optional options
parameter to customize the insertion.
Example MongoDB Insert Many Documents
Let's look at some examples of how to use the insertMany
method in the programGuru
collection in MongoDB:
1. Insert Multiple Documents
db.programGuru.insertMany([
{ name: "John Doe", age: 30, email: "john.doe@example.com" },
{ 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 with the fields name
, age
, and email
into the programGuru
collection.
Full Example
Let's go through a complete example that includes switching to a database, creating a collection, and inserting multiple documents.
Step 1: Switch to a Database
This step involves switching to a database named myDatabase
.
use myDatabase
In this example, we switch to the myDatabase
database.
Step 2: Create a Collection
This step involves creating a new collection named programGuru
in the myDatabase
database.
db.createCollection("programGuru")
Here, we create a collection named programGuru
.
Step 3: Insert Multiple Documents into the Collection
This step involves using the insertMany
method to insert documents into the programGuru
collection.
db.programGuru.insertMany([
{ name: "John Doe", age: 30, email: "john.doe@example.com" },
{ name: "Jane Smith", age: 25, email: "jane.smith@example.com" },
{ name: "Jim Brown", age: 35, email: "jim.brown@example.com" }
])
We insert multiple documents with the fields name
, age
, and email
into the programGuru
collection.
Conclusion
The MongoDB insertMany
operation is crucial for bulk inserting records into collections. Understanding how to use this method allows you to efficiently add and manage large amounts of data within MongoDB collections.