如何在Mongoose中查找具有重复属性的文档?

时间:2019-04-17 11:30:51

标签: mongodb mongoose mongodb-query

我的MongoDB数据库中存储了以下文档(例如集合products):

{
   a: "test1",
   c: "data1"
},
{
   a: "test2",
   c: "data2"
},
{
   a: "test3",
   c: "data1"
},
{
   a: "test4",
   c: "data3"
},
{
   a: "test5",
   c: "data1"
},
{
   a: "test6",
   c: "data3"
},

如何查询属性(c)重复(或重复...)的所有文档?在示例数据中,查询应返回test1, test3, test4, test5 and test6个文档。

1 个答案:

答案 0 :(得分:1)

您可以通过在c上进行分组,然后将分组中有多个分组的分组进行分组:

db.test.aggregate([
    {$group: {_id: '$c', count: {$sum: 1}, docs: {$push: '$$ROOT'}}},
    {$match: {count: {$gt: 1}}}
])
相关问题