Reputation: 990
I have the following document:
"content": [
{
"_id": "5dbef12ae3976a2775851bfb",
"name": "Item AAA",
"itemImages": [
{
"_id": "5dbef12ae3976a2775851bfd",
"imagePath": "https://via.placeholder.com/300",
"imageTitle": "Test 300"
},
{
"_id": "5dbef12ae3976a2775851bfc",
"imagePath": "https://via.placeholder.com/250",
"imageTitle": "Test 250"
}
]
}
and I am wondering if there is a way to return only the data in the array yet with the "name" and document "main _id" so that result set will be
"itemImages": [
{
"_id": "5dbef12ae3976a2775851bfb",
"name": "Item AAA",
"imagePath": "https://via.placeholder.com/300",
"imageTitle": "Test 300"
},
{
"_id": "5dbef12ae3976a2775851bfb",
"name": "Item AAA",
"imagePath": "https://via.placeholder.com/250",
"imageTitle": "Test 250"
}
]
I've tried using mongodb find and aggregate functions but neither helped in retrieving the above results. Thanks for your help
Upvotes: 0
Views: 669
Reputation: 28316
You should be able to get what you want with aggregation.
You'll need to:
This might look something like:
db.collection.aggregate([
{$unwind:"$itemImages"},
{$addFields: {
"itemImages._id":"$_id",
"itemImages.name":"$name"
}},
{$group:{_id:"$_id", itemImages:{$push:"$itemImages"}}},
{$project:{itemImages:1,_id:0}}
])
Upvotes: 1