MongoDB Insert Documents
In this chapter, we will show you how to insert data into MongoDB collections.
The data structure of documents is basically the same as JSON.
All data stored in collections is in BSON format.
BSON is a binary storage format similar to JSON, and is short for Binary JSON.
Common methods for inserting documents include:
| Method | Purpose | Deprecated? |
|---|---|---|
insertOne() | Insert a single document | no |
insertMany() | Insert multiple documents | no |
insert() | Insert single or multiple documents | Yes |
save() | Insert or update a document | Yes |
1、insertOne()
The insertOne() method is used to insert a single document into a collection.
db.collection.insertOne(document, options)
- document: The single document to insert.
- options (optional): An optional parameter object that can include writeConcern, bypassDocumentValidation, etc.
Example
name: "Alice",
age: 25,
city: "New York"
});
Returned result:
{
"acknowledged": true,
"insertedId": ObjectId("60c72b2f9b1d8b5a5f8e2b2d")
}
2、insertMany()
The insertMany() method is used to insert multiple documents into a collection.
db.collection.insertMany(documents, options)
- documents: An array of documents to insert.
- options (optional): An optional parameter object that can include ordered, writeConcern, bypassDocumentValidation, etc.
db.myCollection.insertMany([
{ name: "Bob", age: 30, city: "Los Angeles" },
{ name: "Charlie", age: 35, city: "Chicago" }
]);Returned result:
{
"acknowledged": true,
"insertedIds": [
ObjectId("60c72b2f9b1d8b5a5f8e2b2e"),
ObjectId("60c72b2f9b1d8b5a5f8e2b2f")
]
}
3、db.collection.save()
The save() method behaves similarly to insertOne() when inserting documents.
If the document contains an _id field and it already exists, the document will be updated; if the document does not contain an _id field or the _id does not exist, a new document will be inserted.
Since MongoDB 4.2, db.collection.save() has been marked as deprecated, and the official recommendation is to use db.collection.insertOne() or db.collection.replaceOne() instead.
db.collection.save(document, options)
- document: The document to save.
- options (optional): An optional parameter object that can include writeConcern, etc.
db.myCollection.save({
_id: ObjectId("60c72b2f9b1d8b5a5f8e2b2d"),
name: "David",
age: 40,
city: "San Francisco"
});
Insert Single or Multiple Documents (Old Method)
Use the db.collection.insert() method to insert single or multiple documents.
The insert() method has been marked as deprecated in MongoDB 4.2 and later, and it is recommended to use insertOne() and insertMany().
Syntax:
db.collection.insert(document_or_array)
Parameters:
It can be a document or an array of documents.
1. Insert a single document:
db.users.insert({ name: "David", age: 40, email: "[email protected]" });
2. Insert multiple documents:
db.users.insert([
{ name: "Eve", age: 45, email: "[email protected]" },
{ name: "Frank", age: 50, email: "[email protected]" }
]);
Performance Optimization for Bulk Inserts
If you need to insert a large number of documents, you can use insertMany() and enable theordered: falseoption to improve insertion performance.
Syntax:
db.collection.insertMany([document1, document2, ...], { ordered: false })
Parameters:
ordered: false: Indicates unordered insertion. Even if one document fails to insert, it does not affect the insertion of other documents.
Example
{ name: "Henry", age: 60 },
{ name: "Ivy", age: 65 }
], { ordered: false });
Validation During Insert
MongoDB validates the inserted documents according to the collection's schema validation rules (if defined). If a document does not conform to the rules, the insert operation will fail.
Suppose the users collection has a validation rule that requires the age field to be greater than 0:
db.createCollection("users", {
validator: {
age: { $gt: 0 }
}
});Inserting the following document will fail:
db.users.insertOne({ name: "John", age: -5 }); // 验证失败 Other Extensions