【发布时间】:2020-04-17 03:45:03
【问题描述】:
我有 2 个收藏。文件如下所示。为了便于理解,我删除了其他属性:
集合_A
{
"ref_id" : ObjectId("5e9561edf8beb57100dded8f"),
"features" : [
{
"_id" : ObjectId("5e9561edf8beb57100dded91"),
"k" : "foo",
"v" : "bar"
},
{
"_id" : ObjectId("5e9561edf8beb57100dded92"),
"k" : "foo2",
"v" : "bar2"
}
]
}
Collection_B
{
"ref_id" : ObjectId("5e9561edf8beb57100dded8f")
}
使用聚合我试图在 Collection_B 中找到Collection_B.ref_id == Collection_A.ref_id and Collection_A.features == [{k:foo,v:bar},{k:foo2,v:bar2}] 中的所有文档
基本上将提供的特征数组与 $Collection_A.features 匹配。当 $Collection_A.features 中存在所有提供的功能时,聚合应返回文档。
尝试后,这是我最接近的:
let aggregation_queries = [];
aggregation_queries.push({
$lookup: {
from: "Collection_A",
localField: "ref_id",
foreignField: "ref_id",
as: "Collection_A"
}
});
for(let i = 0; i< features.length; i++)
{
aggregation_queries.push({$match: { $expr: { $in : [features[i].k, "$Collection_A.features.k" ]}}});
}
let aggregateResult = Collection_BSchema.aggregate(aggregation_queries);
这仅匹配 features.k 而不是 features.v。我正在尝试找到一种方法来匹配 fetaures.k 和 features.v,例如 $and: [{features[i].k, "$Collection_A.features.k"}, {features[i].v, "$Collection_A.features.v"}]
我已经搜索并尝试了很多方法,例如 $match 与 $all 但似乎不起作用,因为 match 不支持 $all 例如:"$match":{"$expr":{"$all":["$Collection_A.features",features]} 抛出错误"错误:无法识别的表达式'$all'MongoError:无法识别的表达式"。
有人可以帮忙解决这个问题或提供一些指导吗?
【问题讨论】:
-
Bascally 您正在尝试将所有“CollectionA.features”与您拥有的功能数组匹配。我对吗?例如:-``` [ {a:1,b:2},{a:3,b:4} ]=[ {a:1,b:2},{a:3,b:4} ] ` ``
-
是的,完全正确
-
你试过
$elemMatch吗? -
是的@Joe,我试过了。如果你这样做 $match : { $Collection_A.fetaures: {$elemMatch: fetaures[i]}}} mongo 会抛出一个错误:unknown top level operator: $Collection_A.fetaures
标签: node.js mongodb aggregation-framework