Reputation: 160
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?
Upvotes: 1
Views: 101
Reputation: 36104
$map
to iterate loop of foos
and check _id: 2
condition, if match then return bar
object and merge with current object $mergeObjects
db.collection.aggregate([
{
$project: {
foos: {
$map: {
input: "$foos",
in: {
$cond: [
{ $eq: ["$$this._id", 2] },
{ $mergeObjects: ["$$this", { bar: "$bar" }] },
"$$this"
]
}
}
}
}
}
])
Upvotes: 2