I have a collection like this:
{
\"_id\" : ObjectId(\"5bd1686ba64b9206349284db\"),
\"type\" : \"Package\",
\"codeInstances\" : [
{
You just need to project for name
and description
instead of whole codeInstances
. Check below
db.collection.aggregate([
{ $unwind: "$codeInstances" },
{ $match: { "codeInstances.name": "b", "type": "Package" }},
{ $project: {
"name": "$codeInstances.name",
"description": "$codeInstances.description",
"_id": 0
}}
])
Output:
[
{ "description": "b1", "name": "b" },
{ "description": "b2", "name": "b" },
{ "description": "b3", "name": "b" }
]
You can try below aggregation using $replaceRoot
db.collection.aggregate([
{ "$match": { "codeInstances.name": "b", "type": "Package" }},
{ "$unwind": "$codeInstances" },
{ "$match": { "codeInstances.name": "b", "type": "Package" }},
{ "$replaceRoot": { "newRoot": "$codeInstances" }}
])