首页 > 解决方案 > 在数组 mongodb 中查找重复项

问题描述

我有一个名为 Users 的 Mongo 集合,其结构如下

{
    _id: '1234aaa',
    profile: {
        Organizations: [A,B,C,A,B,A]
    }
},
{
    _id: '1234bbb',
    profile: {
        Organizations: [A,B,C]
    }

},
{
    _id: '1234ccc',
    profile: {
        Organizations: [A,B,C,C]
    }

}

仅当它们在 profile.organizations 下具有重复值时,如何返回我的集合中所有文档的列表。预期的结果是:

DupesUsers: {
    {
        User: '1234aaa,
        Dupes: [A,B]
    },
    {
        User: '1234ccc,
        Dupes: [C]
    },
}

我试过使用 Aggreagte:

db.getCollection('users').aggregate(
  {$unwind: "$profile.organizations"},
  { $project: {_id: '$_id', org: '$profile.organizations'} },
  { $group: {
        _id: null, 
        occurances: {$push: {'org': '$_id', count: '$count'}}
        }
   }
);

但我似乎无法理解它。

标签: mongodbmongooseaggregation-frameworkrobo3t

解决方案


只需进行一些细微的调整,您就离得不远了:

db.getCollection("users").aggregate(
    [
        { 
            "$unwind" : "$profile.organizations"
        }, 
        { 
            "$group" : {
                "_id" : {
                    "dup" : "$profile.organizations", 
                    "id" : "$_id"
                }, 
                "count" : {
                    "$sum" : 1.0
                }
            }
        }, 
        { 
            "$match" : {
                "count" : {
                    "$gt" : 1.0
                }
            }
        }, 
        { 
            "$group" : {
                 _id: "$_id.id",
                 Dupes: {$push: "$_id.dup"}
            }
        }
    ], 
);

推荐阅读