Reputation: 81
I know it's possible to update specific array elements, as documented here: https://docs.mongodb.com/manual/reference/operator/update/positional-filtered/
Also, I'm aware it's possible to use a field value to update the value of another field, as explained here: Update MongoDB field using value of another field
What I need is a combination of the two.
Let's say I have this in the DB:
{
a: [
{
aa: 10
},
{
cc: 15
}
]
}
Now, I want to add a field bb
to the array documents with aa
's value, but only if aa
exists. So the output is:
{
a: [
{
aa: 10,
bb: 10
},
{
cc: 15
}
]
}
How can I achieve this?
Upvotes: 2
Views: 3106
Reputation: 36094
Try update with aggregation pipeline starting from MongoDB 4.2,
$map
to iterate loop of a
array$cond
check condition if aa
field is not null then add new field bb
with value of aa
and merge with current object using $mergeObjects
, otherwise return current objectdb.collection.update(
{ "a.aa": { $exists: true } },
[{
$set: {
a: {
$map: {
input: "$a",
in: {
$cond: [
{ $ne: ["$$this.aa", null] },
{ $mergeObjects: ["$$this", { bb: "$$this.aa" }] }
"$$this",
]
}
}
}
}
}],
{ multi: true }
)
Upvotes: 1