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
Searching for an array entry via its id in a MongoDB collection and performing update
To search for an array via id, use positional $ operator. For update, use the UPDATE in MongoDB. Let us create a collection with documents −
> db.demo49.insertOne(
... {
...
... "Name": "David",
... "Details": [
... {
... "_id": "D1234",
... "Subject":"MySQL"
... },
... {
... "_id": "E234",
... "Subject":"Java"
... },
... {
... "_id": "F456",
... "Subject":"Python"
... }
... ]
... }
... );
{
"acknowledged" : true,
"insertedId" : ObjectId("5e270a77cfb11e5c34d89902")
}
Display all documents from a collection with the help of find() method −
> db.demo49.find();
This will produce the following output −
{ "_id" : ObjectId("5e270a77cfb11e5c34d89902"), "Name" : "David", "Details" : [ { "_id" : "D1234", "Subject" : "MySQL" }, { "_id" : "E234", "Subject" : "Java" }, { "_id" : "F456", "Subject" : "Python" } ] }
Following is the query to search for an array entry via its id in a MongoDB collection −
> db.demo49.update( {"Details._id":"E234"},
... {$set:{"Details.$.Subject":"MongoDB"}}, false, true )
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
Display all documents from a collection with the help of find() method −
> db.demo49.find();
This will produce the following output −
{ "_id" : ObjectId("5e270a77cfb11e5c34d89902"), "Name" : "David", "Details" : [ { "_id" : "D1234", "Subject" : "MySQL" }, { "_id" : "E234", "Subject" : "MongoDB" }, { "_id" : "F456", "Subject" : "Python" } ] }Advertisements