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
Combine update and query parts to form the upserted document in MongoDB?
To combine update and query parts to form an upserted document in MongoDB, use the $set operator with upsert: true. This creates a new document if no match is found, or updates an existing one.
Syntax
db.collection.update(
{ queryCondition },
{ $set: { field: "newValue" } },
{ upsert: true }
);
Sample Data
db.updateWithUpsertDemo.insertMany([
{ "StudentFirstName": "John", "StudentAge": 21 },
{ "StudentFirstName": "Larry", "StudentAge": 23 },
{ "StudentFirstName": "David", "StudentAge": 24 }
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5cd2a61c345990cee87fd890"),
ObjectId("5cd2a624345990cee87fd891"),
ObjectId("5cd2a62c345990cee87fd892")
]
}
Example 1: Update Existing Document
Update Larry's name to "Chris" using upsert ?
db.updateWithUpsertDemo.update(
{ _id: ObjectId("5cd2a624345990cee87fd891") },
{ "$set": { "StudentFirstName": "Chris" } },
{ upsert: true }
);
WriteResult({ "nMatched": 1, "nUpserted": 0, "nModified": 1 })
Example 2: Insert New Document with Upsert
Add a new student "Mike" with age 22 if not exists ?
db.updateWithUpsertDemo.update(
{ "StudentFirstName": "Mike" },
{ "$set": { "StudentFirstName": "Mike", "StudentAge": 22 } },
{ upsert: true }
);
WriteResult({ "nMatched": 0, "nUpserted": 1, "nModified": 0 })
Verify Results
db.updateWithUpsertDemo.find().pretty();
{
"_id": ObjectId("5cd2a61c345990cee87fd890"),
"StudentFirstName": "John",
"StudentAge": 21
}
{
"_id": ObjectId("5cd2a624345990cee87fd891"),
"StudentFirstName": "Chris",
"StudentAge": 23
}
{
"_id": ObjectId("5cd2a62c345990cee87fd892"),
"StudentFirstName": "David",
"StudentAge": 24
}
{
"_id": ObjectId("5cd2a635345990cee87fd893"),
"StudentFirstName": "Mike",
"StudentAge": 22
}
Key Points
-
upsert: truecreates a new document if the query condition finds no match. -
$setensures only specified fields are updated or inserted. - The query condition becomes part of the new document structure during upsert.
Conclusion
Using $set with upsert: true provides flexible document management by updating existing records or creating new ones based on the query condition. This approach combines both query and update operations seamlessly.
Advertisements
