对MongoDB来说是个全新的概念。我有一个名为maProps
的集合,其中保存的文档类似于:
{
"_id" : NumberLong(18),
"custom_branding" : false,
"dashboard_rating" : true,
"ideas_forum" : true,
"membership_domain_restricted" : true
}
我首先想查找集合中custom_branding
值为假或文档上不存在custom_branding
的所有文档
db.getCollection('maProps').aggregate(
[
{$match: {custom_branding: {$ne: false}}}, ......
我有另一个名为bFeatures
的集合,它保存的文档类似于:
{
"_id" : "feature_1_I_want",
"masterAccounts" : [
{
"masterAccountId" : NumberLong(1),
"available" : true,
"enabled" : true
},
{
"masterAccountId" : NumberLong(12),
"available" : false,
"enabled" : false
},
{
"masterAccountId" : NumberLong(13),
"available" : false,
"enabled" : false
},.......
}
所以我相信我在脚本中的下一步是添加一个$lookup
来加入
{$lookup:
{
from: 'betaFeature',
LocalField: '_id',
foreignField: '',
as: "beta",
努力实现:我本质上想首先找到maProps
中custom_branding
为false或字段不存在的所有masterAccounts
。然后使用主帐户的信息,转到bFeatures
,找到一个与feature_1_I_want
匹配的_id
,我们在maProps
中匹配的所有masterAccounts
-将它们添加到集合文档中,其中available
和enabled
设置为true的masterAccounts
:
{
"_id" : "feature_1_I_want",
"masterAccounts" : [
{
"masterAccountId" : NumberLong(1),
"available" : true,
"enabled" : true
},
{
"masterAccountId" : NumberLong(12),
"available" : false,
"enabled" : false
},
{
"masterAccountId" : NumberLong(13),
"available" : false,
"enabled" : false
},.......<I would add the MA's here with available true and enabled true>
}
我不确定实现这一目标的最佳/最有效的方法是什么。我也尝试过使用管道,但不清楚它们是如何工作的。如有任何建议和指导,我们将不胜感激。
您可以从下面的查询开始。它在第一阶段生成match
,然后通过从betaFeature
集合中过滤仅具有"masterAccounts.available":true
和masterAccounts.enabled":true
的文档来执行嵌套管道的查找
db.getCollection('maProps').aggregate([
{$match: {custom_branding: false}},
{$lookup:
{
from: 'betaFeature',
let: { beta_id: "$_id" },
pipeline: [
{ $match:
{ $expr:
{ $and:
[
{ $eq: [ "$_id", "$$beta_id" ] },
{ $eq: [ "$masterAccounts.available", true ] },
{ $eq: [ "$masterAccounts.enabled", true ] },
]
}
}
},
{ $project: { _id: 0 } }
]
as: "beta_accounts"}}
])