[英]MongoDB aggregation filtering of a nested object
我需要過濾一組嵌套對象,並且只返回那些將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
,但由於它是嵌套的,因此無法完成。 另外,如果有另一種方法,我全聽。
您需要在 $match 主 _id 后展開“訂閱”數組,之后您需要在活動郵件上再次 $match 。 使用 $project 創建更好的輸出。 確保您只查詢一個主要的 _id,否則這會因潛在不同用戶的多個項目而變得混亂。
db.subscriptions.aggregate([
{
$match: { _id: ObjectId('5f9a4f3170bd08b002498d44') },
},
{
$unwind: {
path: '$subscriptions',
},
},
{
$match: {
'subscriptions.active.email': true,
},
},
{
$project: {
activeUserId: '$subscriptions.user',
_id: 0,
},
},
])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.