Raman S
Raman S

Reputation: 39

Update one property of Nested MongoDB array with another

I have a document in mongo like this:

{
"parentId":"1234",
"otherParentProperty":"someProperty",
"nestedArray":[
{
"propertyId":"1234"
"property1":null,
"property2":"some value"
},
{
"propertyId":"5678"
"property1":null,
"property2":"some other value"
}
]
}

How can I copy the value of property2 for each element and set it in the corresponding property1? So the end result will be like :

{
"parentId":"1234",
"otherParentProperty":"someProperty",
"nestedArray":[
{
"propertyId":"1234"
"property1":"some value",
"property2":"some value"
},
{
"propertyId":"5678"
"property1":"some other value",
"property2":"some other value"
}
]
}

Upvotes: 0

Views: 47

Answers (1)

prasad_
prasad_

Reputation: 14317

Using the input documents:

{ "_id" : 1, "arr" : [ { p1: 1, p2: 11 }, { p1: 2, p2: 22 } ] },
{ "_id" : 2, "arr" : [ { p1: 9, p2: 99 } ] }

The following aggregation query will update all documents - the field value of arr.p1 is replaced with the value of the field value of arr.p2 for all elements of the array.

db.test.aggregate( [
  { $project: { 
         arr: { 
             $map: {
                  input: "$arr",
                     as: "e",
                     in: { $mergeObjects: [ "$$e", { p1: "$$e.p2" } ] }
             }
        } 
  } }
] 
).forEach( doc => db.test.updateOne( { _id: doc._id }, { $set: { arr: doc.arr } } ) )

The resulting documents in the updated collection:

{ "_id" : 1, "arr" : [ { "p1" : 11, "p2" : 11 }, { "p1" : 22, "p2" : 22 } ] }
{ "_id" : 2, "arr" : [ { "p1" : 99, "p2" : 99 } ] }


- OR -

If you are using MongoDB 4.2 or later you can use this updateMany method:

db.test.updateMany(
{ },
[
  { $set: { 
         arr: { 
             $map: {
                  input: "$arr",
                     as: "e",
                     in: { $mergeObjects: [ "$$e", { p1: "$$e.p2" } ] }
             }
        } 
  } }
]
)

Upvotes: 1

Related Questions