MongoDB query to update an array using FindAndUpdate()?


To update an array, instead use findAndModify() in MongoDB. Let us create a collection with documents −

> db.demo152.insertOne({"id":102,"Name":["Chris","David"],Score:45});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e3515bcfdf09dd6d08539dd")
}
> db.demo152.insertOne({"id":103,"Name":["Mike","Carol"],Score:65});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e3515cafdf09dd6d08539de")
}

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

> db.demo152.find();

This will produce the following output −

{ "_id" : ObjectId("5e3515bcfdf09dd6d08539dd"), "id" : 102, "Name" : [ "Chris", "David" ], "Score" : 45 }
{ "_id" : ObjectId("5e3515cafdf09dd6d08539de"), "id" : 103, "Name" : [ "Mike", "Carol" ], "Score" : 65 }

Following is the query to update an array −

> var d = db.demo152.findAndModify({
...    query: {
...       id:102,
...       Score: {$lt:50},
...       Name: "Chris"
...    },
...    update: {
...       $set : {"Name.$": "Robert"},
...       $inc: {Score: 20 }
...       }
...    }
...
... )

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

> db.demo152.find();

This will produce the following output −

{ "_id" : ObjectId("5e3515bcfdf09dd6d08539dd"), "id" : 102, "Name" : [ "Robert", "David" ], "Score" : 65 }
{ "_id" : ObjectId("5e3515cafdf09dd6d08539de"), "id" : 103, "Name" : [ "Mike", "Carol" ], "Score" : 65 }

Updated on: 01-Apr-2020

304 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements