How to update value of a key in a list of a json in MongoDB?

MongoDBDatabaseBig Data Analytics

Let us first create a collection with documents

> db.updateListOfKeyValuesDemo.insertOne( { "StudentDetails":[ { "StudentName":"John", "StudentAge":23, "StudentCountryName":"US" }, { "StudentName":"Carol", "StudentAge":24, "StudentCountryName":"UK" }, { "StudentName":"Bob", "StudentAge":22, "StudentCountryName":"AUS" } ] } );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c9b5b759882024390176545")
}

Following is the query to display all documents from a collection with the help of find() method

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

This will produce the following output

{
   "_id" : ObjectId("5c9b5b759882024390176545"),
   "StudentDetails" : [
      {
         "StudentName" : "John",
         "StudentAge" : 23,
         "StudentCountryName" : "US"
      },
      {
         "StudentName" : "Carol",
         "StudentAge" : 24,
         "StudentCountryName" : "UK"
      },
      {
         "StudentName" : "Bob",
         "StudentAge" : 22,
         "StudentCountryName" : "AUS"
      }
   ]
}

Following is the query to update value of a key in a list of a json in MongoDB

> var documentFromCollection = db.updateListOfKeyValuesDemo.findOne({
...    "_id": ObjectId("5c9b5b759882024390176545")
... });
>
> documentFromCollection.StudentDetails.forEach(function(updateStudent) {
...    updateStudent.StudentName = "Ramit";
... });
> db.updateListOfKeyValuesDemo.update(
...    { "_id": documentFromCollection ._id },
...    { "$set": { "StudentDetails": documentFromCollection.StudentDetails } }
... );
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

Let us check the list of key values has been updated or not

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

This will produce the following output

{
   "_id" : ObjectId("5c9b5b759882024390176545"),
   "StudentDetails" : [
      {
         "StudentName" : "Ramit",
         "StudentAge" : 23,
         "StudentCountryName" : "US"
      },
      {
         "StudentName" : "Ramit",
         "StudentAge" : 24,
         "StudentCountryName" : "UK"
      },
      {
         "StudentName" : "Ramit",
         "StudentAge" : 22,
         "StudentCountryName" : "AUS"
      }
   ]
}
raja
Updated on 30-Jul-2019 22:30:25

Advertisements