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
Update key value where another key equals some value in MongoDB?
Use $elemMatch fir this with $set
Let us first create a collection with documents −
> dbkeyValueDemoinsertOne(
{
"_id" : new ObjectId(),
"CustomerDetails" : [
{
"Name" : "Chris",
"Age" :24,
},
{
"Name" : "Robert",
"Age" :29,
},
{
"Name" : "David",
"Age" :35,
}
]
}
);
{
"acknowledged" : true,
"insertedId" : ObjectId("5cefcf36ef71edecf6a1f6bf")
}
Following is the query to display all documents from a collection with the help of find() method −
> dbkeyValueDemofind()pretty();
Output
{
"_id" : ObjectId("5cefcf36ef71edecf6a1f6bf"),
"CustomerDetails" : [
{
"Name" : "Chris",
"Age" : 24
},
{
"Name" : "Robert",
"Age" : 29
},
{
"Name" : "David",
"Age" : 35
}
]
}
Here is the query to update key value where different key equals some value −
> dbkeyValueDemoupdate(
{"CustomerDetails":{"$elemMatch":{"Name":"David"}}},
{"$set":{"CustomerDetails$Age":56}});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 }
)
Let us check the document once again −
> dbkeyValueDemofind()pretty();
Output
{
"_id" : ObjectId("5cefcf36ef71edecf6a1f6bf"),
"CustomerDetails" : [
{
"Name" : "Chris",
"Age" : 24
},
{
"Name" : "Robert",
"Age" : 29
},
{
"Name" : "David",
"Age" : 56
}
]
}Advertisements