0

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"
}
]
}

1 Answer 1

1

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" } ] }
             }
        } 
  } }
]
)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.