我需要过滤一组嵌套对象,只返回将active.email
设置为true的对象。
到目前为止,我有一个汇总:
db.subscriptions.aggregate([
{
$match: { user: ObjectId('5f9a4f3070bd08b002498d43') },
},
{
$project: {
'subscriptions.user': 1,
'subscriptions.active.email': 1,
},
})
哪个返回单个用户的订阅文档:
{
"_id" : ObjectId("5f9a4f3170bd08b002498d44"),
"subscriptions" : [
{
"active" : {
"email" : true
},
"user" : ObjectId("5f9a4e5071713dc6120df47f")
},
{
"active" : {
"email" : true
},
"user" : ObjectId("5f9b7f2dc16811a281113ba1")
},
{
"active" : {
"email" : false
},
"user" : ObjectId("5f9b7e8ac16811a281113b9f")
}
]
}
如果我尝试在其上使用过滤器:
db.subscriptions.aggregate([
{
$match: { user: ObjectId('5f9a4f3070bd08b002498d43') },
},
{
$project: {
'subscriptions.user': 1,
'subscriptions.active.email': 1,
},
},
{
$filter: {
input: '$subscriptions',
as: 'subs',
cond: { '$$subs.active.email': true },
},
},
它给了我这个错误:"Unrecognized pipeline stage name: '$filter'",
这是我想要的输出:
"subscriptions" : [
{
"active" : {
"email" : true
},
"user" : ObjectId("5f9a4e5071713dc6120df47f")
},
{
"active" : {
"email" : true
},
"user" : ObjectId("5f9b7f2dc16811a281113ba1")
},
]
在此使用过滤器的正确方法是什么?我最初尝试在查询中使用$elemMatch
,但是由于它是嵌套的,因此无法完成。另外,如果有另一种方法,我会很烦。
答案 0 :(得分:1)
在与主_id进行$ match匹配之后,您需要展开“订阅”数组,之后,您需要在活动邮件上再次进行$ match匹配。使用$ project创建更好的输出。确保只查询一个主_id,否则可能会混淆多个潜在的不同用户项。
db.subscriptions.aggregate([
{
$match: { _id: ObjectId('5f9a4f3170bd08b002498d44') },
},
{
$unwind: {
path: '$subscriptions',
},
},
{
$match: {
'subscriptions.active.email': true,
},
},
{
$project: {
activeUserId: '$subscriptions.user',
_id: 0,
},
},
])