
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 Different Key Equals Some Value in MongoDB
Let us create a collection with documents −
> db.demo196.insertOne( ... { ... ... "Id" : "101", ... "details" : [ ... { ... "FirstName" : "Chris", ... "LastName" : "Brown", ... "Score" : 45 ... }, ... { ... "FirstName" : "David", ... "LastName" : "Miller", ... "Score" : 87 ... }, ... { ... "FirstName" : "John", ... "LastName" : "Doe", ... "Score" : 56 ... } ... ] ... } ...); { "acknowledged" : true, "insertedId" : ObjectId("5e3af6b103d395bdc21346d7") }
Display all documents from a collection with the help of find() method −
> db.demo196.find();
This will produce the following output −
{ "_id" : ObjectId("5e3af6b103d395bdc21346d7"), "Id" : "101", "details" : [ { "FirstName" : "Chris", "LastName" : "Brown", "Score" : 45 }, { "FirstName" : "David", "LastName" : "Miller", "Score" : 87 }, { "FirstName" : "John", "LastName" : "Doe", "Score" : 56 } ] }
Following is the query to update key value where different key equals some value −
> db.demo196.update({"details":{"$elemMatch":{"FirstName" : "David", "LastName" : "Miller"}}}, ... {"$set":{"details.$.Score":98}}); WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
Display all documents from a collection with the help of find() method −
> db.demo196.find();
This will produce the following output −
{ "_id" : ObjectId("5e3af6b103d395bdc21346d7"), "Id" : "101", "details" : [ { "FirstName" : "Chris", "LastName" : "Brown", "Score" : 45 }, { "FirstName" : "David", "LastName" : "Miller", "Score" : 98 }, { "FirstName" : "John", "LastName" : "Doe", "Score" : 56 } ] }
Advertisements