How to update document under nested arrays

Hello, I have these sample documents, MongoDB version 3.6, how to update this document from fname “aayushi” to “abc”. I tried it with aggregation using $unwind, but that is not changing its field in the collection, it is not updating in the collection, just projecting new updated field. Help is appreciable.

sample documents:
db.col.find()

{ “_id” : ObjectId(“5e24815e386cb1760439e72f”), “details” : [ { “name” : [ { “fname” : “aayushi” }, { “lname” : “agrawal” } ] } ] }

{ “_id” : ObjectId(“5e24817a386cb1760439e730”), “details” : [ { “name” : [ { “fname” : “john” }, { “lname” : “anthony” } ] } ] }

Here is my test:
db.customerOrder.aggregate([ {
$unwind: “$details”
}, {
$unwind: “$details.name”
}, {
$match: {
“details.name.fname”: “aayushi”
}
},
{
$project: {
“details.name.fname”: 1
}
} ]).pretty();

Hi @AayushiMangal,

aggregate will not update the existing field. However, if you want to update only single document, you can do it using update command like:

   db.agg.update({"details.name.fname": "aayushi"}, {"details.name.fname": "abc"}) 

Kanika

1 Like