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" } ] }

Updated on: 03-Apr-2020

63 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements