MongoDB - 通过多个键查找重复文档

时间:2016-09-14 12:45:57

标签: mongodb mongodb-query aggregation-framework mongodb-aggregation

我有一个包含如下文档的集合:

{
        "_id" : ObjectId("55b377cb66b393427367c3e2"),
        "comment" : "This is a comment",
        "url_key" : "55b377cb66b393427367c3df", //This is an ObjectId from another record in a different collection
}

我需要在此集合中查找包含注释和url_key的重复值的记录。

我可以轻松地为相同的单个键生成(使用聚合)重复记录(例如:注释),但我无法弄清楚如何按多个键分组/聚合。

这是我当前的聚合管道:

db.comments.aggregate([ { $group: { _id: { comment: "$comment" }, uniqueIds: { $addToSet: "$_id" }, count: { $sum: 1 } } }, { $match: { count: { $gte: 2 } } }, { $sort: { count : -1} }, {$limit 10 } ]);

1 个答案:

答案 0 :(得分:4)

是否像通过多个键分组一样简单,还是我误解了你的问题?

...
{ $group: { _id: { id: "$_id", comment: "$comment" }, count: { $sum: 1 } } },
{ $match: { count: { $gte: 2 } } },
...
相关问题