MongoDB query to replace value in an array?


Use $set to replace value in an array. Let us first create a collection with documents −

> db.replaceValueInArrayDemo.insertOne({"StudentScores":[45,56,78]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd7f0421a844af18acdffb7")
}
> db.replaceValueInArrayDemo.insertOne({"StudentScores":[33,90,67]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd7f0521a844af18acdffb8")
}

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

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

This will produce the following output −

{
   "_id" : ObjectId("5cd7f0421a844af18acdffb7"),
   "StudentScores" : [
      45,
      56,
      78
   ]
}
{
   "_id" : ObjectId("5cd7f0521a844af18acdffb8"),
   "StudentScores" : [
      33,
      90,
      67
   ]
}

Following is the query to replace value in array −

> db.replaceValueInArrayDemo.update({_id: ObjectId("5cd7f0421a844af18acdffb7"), StudentScores:45}, {$set: {'StudentScores.$': 99}});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

Let us check the document once again −

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

This will produce the following output −

{
   "_id" : ObjectId("5cd7f0421a844af18acdffb7"),
   "StudentScores" : [
      99,
      56,
      78
   ]
}
{
   "_id" : ObjectId("5cd7f0521a844af18acdffb8"),
   "StudentScores" : [
      33,
      90,
      67
   ]
}

Updated on: 30-Jul-2019

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements