【发布时间】:2020-05-27 17:54:06
【问题描述】:
我有一个收集文件说测试:
{id: 123,
lId: abc,
cnum: [{num: 112, type:R}]
},
{id: 234,
lId: abc,
cnum:[{ num: 112, type: R}]
},
{id: 345,
lId: cbd,
cnum: [{num: 112, type: R}]
},
{id: 456,
lId: efg,
cnum: [{num: 121, type:R}]
}
我希望查询返回具有重复 cnum 的 num 值但唯一 lId 的值。那就是它应该返回
id: 123,lId: abc, cnum.num: 112, id: 345,lId: cbd, cnum.num: 112
但目前它正在返回
id: 123,lId: abc,cnum.num: 112, id: 234, lId: abc, cnum.num: 112, id: 345,lId: cbd, cnum.num: 112
我当前的脚本也返回了重复的 lId。这是我的脚本:
var groupCnum = db.getCollection('test').aggregate([
{ $match: {"cnum.0": {$exists: true}}},
{ $unwind: "$cnum" },
{ $match: { "cnum.type": "R" } },
{ $group: { "_id": "$cnum.num", "count": { $sum: 1 } } },
{ $match: {"count": {"$gt": 1} } }
], {allowDiskUse: true}).map(record => record._id);
var duplicatedCnum = db.getCollection('test').aggregate([
{ $match: {"lId": {$nin: groupCnum}}},
{ $match: { "cnum.num": {$in: groupCnum} } },
{ $unwind: "$cnum" },
{ $match: { "cnum.type": "R" } },
{ $sort: {cnum: 1} },
{ $limit: 100}
], {allowDiskUse: true});
var fieldNames = ["id", "lId", "cnum.num"];
print(fieldNames.join(","));
谁能建议我错过了什么?
【问题讨论】:
-
您提供的示例文档和您正在使用的查询中的类型不匹配,例如来自查询
cnum的查询似乎是一个数组。另外,您如何从该聚合中获取这些返回类型超出了我的范围,因为您没有对ltd字段进行分组,所以我不确定发生了什么。如果你能把事情弄清楚 -
@TomSlabbaert 是的,cnum 是一个数组,很抱歉造成混淆,我已经更新了示例文档。我没有得到上面的返回值,它只是返回值的一个示例。为了清楚起见,我也更新了它。我也不确定如何先按
lId分组,然后按cnum分组。可能这就是我无法正确理解的。 -
你能解释一下为什么你不希望所有的文件都归还吗?好像都符合你的要求
-
@TomSlabbaert 我的要求是获取具有不同
lId的重复cnum值。所以基本上如果 2 个独特的lId共享相同的cnum。
标签: mongodb mongodb-query aggregation-framework