我有以下数据
{
"_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":[
]
}
对Retrieve all embedded Request objects that have active = true
执行如下查询。
db.groups.aggregate(
[
{ $project : { "requests" : 1 }},
{ $unwind : "$requests" },
{ $project: {
"requests": {
"$filter": {
"input": "$requests",
"as": "item",
"cond": { $eq: [ "$$item.active",true ] }
}
}
}
}
]
)
我做错了什么?
如果我做下面的
是否会更容易(相同)?[
{ $project : { "requests" : 1 }},
{ $unwind : "$requests" },
{ $match : { "requests.active" : true } }
]
您只需要从管道中删除$unwind
级:
db.groups.aggregate(
[
{ $project: {
"requests": {
"$filter": {
"input": "$requests",
"as": "item",
"cond": { $eq: [ "$$item.active",true ] }
}
}
}
}
]
)
否则$unwind
将requests
字段从数组更改为单个对象,因为它复制了$filter
不能使用的文档。