MongoDB查询-匹配,查找,然后



对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",

努力实现:我本质上想首先找到maPropscustom_branding为false或字段不存在的所有masterAccounts。然后使用主帐户的信息,转到bFeatures,找到一个与feature_1_I_want匹配的_id,我们在maProps中匹配的所有masterAccounts-将它们添加到集合文档中,其中availableenabled设置为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":truemasterAccounts.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"}}


])

最新更新