Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Combine update and query parts to form the upserted document in MongoDB?
You need to use $set operator along with upsert:true. Let us first create a collection with documents −
> db.updateWithUpsertDemo.insertOne({"StudentFirstName":"John","StudentAge":21});
{
"acknowledged" : true,
"insertedId" : ObjectId("5cd2a61c345990cee87fd890")
}
> db.updateWithUpsertDemo.insertOne({"StudentFirstName":"Larry","StudentAge":23});
{
"acknowledged" : true,
"insertedId" : ObjectId("5cd2a624345990cee87fd891")
}
> db.updateWithUpsertDemo.insertOne({"StudentFirstName":"David","StudentAge":24});
{
"acknowledged" : true,
"insertedId" : ObjectId("5cd2a62c345990cee87fd892")
}
Following is the query to display all documents from a collection with the help of find() method −
> db.updateWithUpsertDemo.find().pretty();
This will produce the following output −
{
"_id" : ObjectId("5cd2a61c345990cee87fd890"),
"StudentFirstName" : "John",
"StudentAge" : 21
}
{
"_id" : ObjectId("5cd2a624345990cee87fd891"),
"StudentFirstName" : "Larry",
"StudentAge" : 23
}
{
"_id" : ObjectId("5cd2a62c345990cee87fd892"),
"StudentFirstName" : "David",
"StudentAge" : 24
}
Following is the query to combine update and query parts to form the upserted document −
> db.updateWithUpsertDemo.update({_id: ObjectId("5cd2a624345990cee87fd891")},{"$set": {"StudentFirstName": "Chris"}}, {upsert:true});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
Let us check whether the field “StudentFirstName” has been changed or not −
> db.updateWithUpsertDemo.find().pretty();
This will produce the following output −
{
"_id" : ObjectId("5cd2a61c345990cee87fd890"),
"StudentFirstName" : "John",
"StudentAge" : 21
}
{
"_id" : ObjectId("5cd2a624345990cee87fd891"),
"StudentFirstName" : "Chris",
"StudentAge" : 23
}
{
"_id" : ObjectId("5cd2a62c345990cee87fd892"),
"StudentFirstName" : "David",
"StudentAge" : 24
}Advertisements