Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Upsert many documents in MongoDB
To upsert many documents in MongoDB, use bulk operations with the upsert() option. This allows you to update multiple documents if they exist, or insert new ones if they don't match the query criteria.
Syntax
var bulk = db.collection.initializeUnorderedBulkOp();
bulk.find({queryCondition}).upsert().update({
$setOnInsert: {fieldsForNewDocuments},
$set: {fieldsToUpdate}
});
bulk.execute();
Sample Data
Let us create a collection with duplicate documents −
db.demo425.insertMany([
{"Name": "Chris", "Age": 21},
{"Name": "David", "Age": 23},
{"Name": "Chris", "Age": 21},
{"Name": "Chris", "Age": 21}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5e74ee4fbbc41e36cc3cae6c"),
ObjectId("5e74ee56bbc41e36cc3cae6d"),
ObjectId("5e74ee57bbc41e36cc3cae6e"),
ObjectId("5e74ee5cbbc41e36cc3cae6f")
]
}
Display all documents from the collection −
db.demo425.find();
{"_id": ObjectId("5e74ee4fbbc41e36cc3cae6c"), "Name": "Chris", "Age": 21}
{"_id": ObjectId("5e74ee56bbc41e36cc3cae6d"), "Name": "David", "Age": 23}
{"_id": ObjectId("5e74ee57bbc41e36cc3cae6e"), "Name": "Chris", "Age": 21}
{"_id": ObjectId("5e74ee5cbbc41e36cc3cae6f"), "Name": "Chris", "Age": 21}
Example: Upsert Multiple Documents
Update all documents with Name "Chris" to "Robert" using bulk upsert operation −
var bulk = db.demo425.initializeUnorderedBulkOp();
bulk.find({Name: "Chris"}).upsert().update({
$setOnInsert: {id: 101},
$set: {Name: "Robert", Age: 23}
});
bulk.execute();
BulkWriteResult({
"writeErrors": [],
"writeConcernErrors": [],
"nInserted": 0,
"nUpserted": 0,
"nMatched": 3,
"nModified": 3,
"nRemoved": 0,
"upserted": []
})
Verify Result
Display all documents to see the updated results −
db.demo425.find();
{"_id": ObjectId("5e74ee4fbbc41e36cc3cae6c"), "Name": "Robert", "Age": 23}
{"_id": ObjectId("5e74ee56bbc41e36cc3cae6d"), "Name": "David", "Age": 23}
{"_id": ObjectId("5e74ee57bbc41e36cc3cae6e"), "Name": "Robert", "Age": 23}
{"_id": ObjectId("5e74ee5cbbc41e36cc3cae6f"), "Name": "Robert", "Age": 23}
Key Points
-
$setOnInsertsets values only when a new document is inserted (upserted) -
$setupdates fields in both existing and newly inserted documents -
nMatched: 3shows that 3 existing documents were found and updated -
nUpserted: 0indicates no new documents were inserted in this case
Conclusion
Bulk upsert operations efficiently handle multiple document updates or inserts in a single operation. Use $setOnInsert for new document fields and $set for universal updates across all matching documents.
Advertisements
