Reputation: 9222
I have the following data
{
"_id":"57b5271231a5a203f8815e78",
"name":"Group A",
"created":new Date(1471489810155),
"active":true,
"invites":[
],
"requests":[
{
"_id":"57b683e531a5a21679b78e6c",
"created":new Date(1471579109215),
"user_id":"57b4c5f0291ebb23110b888e",
"description":"Request From John",
"active":true,
"date": new Date("2016-08-23T13:58:15-0700 "),
" denied_users":[
]
},
{
"_id":"57b683e531a5a21679a78e6c",
"created":new Date(1471579109215),
"user_id":"57b4c5f0291ebb13110b888e",
"description":"Request A",
"active":true,
"date": new Date("2016-08-23T13:58:15-0700 "),
" denied_users":[
]
},
{
"_id":"57b6841231a5a21679a78e6d",
"created":new Date(1471579154271),
"user_id":"57b4c5f0291ebb13110b888e",
"description":"Request B",
"active":true,
"date": new Date("2016-08-26T13:59:07-0700 "),
" denied_users":[
]
}
],
"fulfillments":[
]
}
And am running the following query to Retrieve all embedded Request objects that have active = true
. Nothing is being returned though.
db.groups.aggregate(
[
{ $project : { "requests" : 1 }},
{ $unwind : "$requests" },
{ $project: {
"requests": {
"$filter": {
"input": "$requests",
"as": "item",
"cond": { $eq: [ "$$item.active",true ] }
}
}
}
}
]
)
What am I doing wrong?
UPDATE
Would it be easier(the same) if I did the following
[
{ $project : { "requests" : 1 }},
{ $unwind : "$requests" },
{ $match : { "requests.active" : true } }
]
Upvotes: 0
Views: 2272
Reputation: 311895
You just need to remove the $unwind
stage from your pipeline:
db.groups.aggregate(
[
{ $project: {
"requests": {
"$filter": {
"input": "$requests",
"as": "item",
"cond": { $eq: [ "$$item.active",true ] }
}
}
}
}
]
)
Otherwise the $unwind
changes the requests
field from an array into a single object as it duplicates the docs which can't be used with $filter
.
Upvotes: 3