Update a specific MongoDB document in array with $set and positional $ operator?


To update a specific document in array with $set and positional $ operator, use MongoDB updateOne(). The updateOne() updates a single document in a collection based on a query filter.

Let us create a collection with documents −

> db.demo462.insertOne(
... {
...    "id":1,
...    "DueDateDetails": [
...       {
...          "Name": "David",
...          "Age":21,
...          "CountryName":["US","UK"]
...       },
...       {
...
...          "Name": "Chris",
...          "Age":23,
...          "CountryName":["UK"]
...       }
...    ]
... }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e7f6c59cb66ccba22cc9dce")
}

Display all documents from a collection with the help of find() method −

> db.demo462.find();

This will produce the following output −

{ "_id" : ObjectId("5e7f6c59cb66ccba22cc9dce"), "id" : 1, "DueDateDetails" : [ { "Name" :
"David", "Age" : 21, "CountryName" : [ "US", "UK" ] }, { "Name" : "Chris", "Age" : 23,
"CountryName" : [ "UK" ] } ] }

Following is the query to update document in array using $set and positional $ operator with updateOne() −

> db.demo462.updateOne(
...    {id: 1, "DueDateDetails.Name": "Chris"},
...    { $set: { "DueDateDetails.$.CountryName": "AUS"} }
... )
{ "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 1 }

Display all documents from a collection with the help of find() method −

> db.demo462.find().pretty();

This will produce the following output −

{
   "_id" : ObjectId("5e7f6c59cb66ccba22cc9dce"),
   "id" : 1,
   "DueDateDetails" : [
      {
         "Name" : "David",
         "Age" : 21,
         "CountryName" : [
            "US",
            "UK"
         ]
      },
      {
         "Name" : "Chris",
         "Age" : 23,
         "CountryName" : "AUS"
      }
   ]
}

Updated on: 11-May-2020

169 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements