Here's my data:
{
foos: [
{ _id: 1 },
{ _id: 2 },
{ _id: 3 }
],
bar: "baz"
}
Now I wanna move field bar into foos object with _id = 2 to have this:
{
foos: [
{ _id: 1 },
{ _id: 2, bar: "baz" },
{ _id: 3 },
]
}
How can I do this using aggregation framework?
$map to iterate loop of foos and check _id: 2 condition, if match then return bar object and merge with current object $mergeObjectsdb.collection.aggregate([
{
$project: {
foos: {
$map: {
input: "$foos",
in: {
$cond: [
{ $eq: ["$$this._id", 2] },
{ $mergeObjects: ["$$this", { bar: "$bar" }] },
"$$this"
]
}
}
}
}
}
])