Computer >> Computer tutorials >  >> Programming >> MongoDB

Update the last row with search criteria in MongoDB?


To update with search criteria, use findAndModify() in MongoDB. Let us create a collection with documents −

> db.demo516.insertOne({"Name":"John","Age":22,"Score":56});{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e889fdb987b6e0e9d18f591")
}
> db.demo516.insertOne({"Name":"John","Age":23,"Score":67});{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e889ff1987b6e0e9d18f592")
}
> db.demo516.insertOne({"Name":"John","Age":22,"Score":56});{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e889ff3987b6e0e9d18f593")
}
> db.demo516.insertOne({"Name":"John","Age":22,"Score":66});{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e889ffa987b6e0e9d18f594")
}

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

> db.demo516.find();

This will produce the following output −

{ "_id" : ObjectId("5e889fdb987b6e0e9d18f591"), "Name" : "John", "Age" : 22, "Score" : 56 }
{ "_id" : ObjectId("5e889ff1987b6e0e9d18f592"), "Name" : "John", "Age" : 23, "Score" : 67 }
{ "_id" : ObjectId("5e889ff3987b6e0e9d18f593"), "Name" : "John", "Age" : 22, "Score" : 56 }
{ "_id" : ObjectId("5e889ffa987b6e0e9d18f594"), "Name" : "John", "Age" : 22, "Score" : 66 }

Following is the query to update the last row with search criteria in MongoDB −

> db.demo516.findAndModify({
... query: {Name: "John", Age: 22},
... sort: {_id: -1},
... update: {$set: {Score: 98}},
... new: true
... })
{
   "_id" : ObjectId("5e889ffa987b6e0e9d18f594"),
   "Name" : "John",
   "Age" : 22,
   "Score" : 98
}

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

> db.demo516.find();

This will produce the following output −

{ "_id" : ObjectId("5e889fdb987b6e0e9d18f591"), "Name" : "John", "Age" : 22, "Score" : 56 }
{ "_id" : ObjectId("5e889ff1987b6e0e9d18f592"), "Name" : "John", "Age" : 23, "Score" : 67 }
{ "_id" : ObjectId("5e889ff3987b6e0e9d18f593"), "Name" : "John", "Age" : 22, "Score" : 56 }
{ "_id" : ObjectId("5e889ffa987b6e0e9d18f594"), "Name" : "John", "Age" : 22, "Score" : 98 }