MongoDB Insert Documents
In this chapter, we will introduce how to insert data into a MongoDB collection.
The data structure of a document is basically the same as JSON.
All data stored in a collection is in BSON format.
BSON is a binary-form storage format similar to JSON, and is short for Binary JSON.
Commonly used methods for inserting documents include:
| Method | Purpose | Deprecated or not |
|---|---|---|
insertOne() |
Insert a single document | No |
insertMany() |
Insert multiple documents | No |
insert() |
Insert one or multiple documents | Is |
save() |
Insert or update a document | Is |
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, and so on.
Example
db.
myCollection
.
insertOne
(
{
name
:
"Alice"
,
age
:
25
,
city
:
"New York"
}
)
;
Return 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, and so on.
db.myCollection.insertMany([
{ name: "Bob", age: 30, city: "Los Angeles" },
{ name: "Charlie", age: 35, city: "Chicago" }
]);
Return 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 that already exists, the document is updated; if the document does not contain an _id field or the _id does not exist, a new document is inserted.
Starting from 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, and so on.
db.myCollection.save({
_id: ObjectId("60c72b2f9b1d8b5a5f8e2b2d"),
name: "David",
age: 40,
city: "San Francisco"
});
Insert one or multiple documents (old method)
Use the db.collection.insert() method to insert one or multiple documents.
The insert() method has been marked as deprecated in MongoDB 4.2 and later; insertOne() and insertMany() are recommended instead.
Syntax:
db.collection.insert(document_or_array)
Parameters:
-
It can be a single document or an array of documents.
1. Insert a single document:
db.users.insert({ name: "David", age: 40, email: "david@example.com" });
2. Insert multiple documents:
db.users.insert([
{ name: "Eve", age: 45, email: "eve@example.com" },
{ name: "Frank", age: 50, email: "frank@example.com" }
]);
Performance optimization for bulk inserts
If you need to insert a large number of documents, you can use insertMany() with the ordered: false option enabled to improve insert performance.
Syntax:
db.collection.insertMany([document1, document2, ...], { ordered: false })
Parameters:
-
ordered: false: Indicates an unordered insert; even if one document fails to insert, it does not affect the insertion of other documents.
Example
db.
users
.
insertMany
(
[
{
name
:
"Henry"
,
age
:
60
}
,
{
name
:
"Ivy"
,
age
:
65
}
]
,
{
ordered
:
false
}
)
;
Validation on insert
MongoDB validates inserted documents against the collection's schema validation rules (if defined). If a document does not conform to the rules, the insert operation fails.
Suppose the users collection has a validation rule requiring the age field to be greater than 0:
db.createCollection("users", {
validator: {
age: { $gt: 0 }
}
});
Inserting the following document would fail:
db.users.insertOne({ name: "John", age: -5 }); // 验证失败