查找数组中的重复项

Find duplicate entries in array

我不小心导入了一些文件,现在有重复的 "slugs" 。

我正在使用 mongoid,所以我的模型看起来像这样:

class 我的模型 字段:名称,字符串# "My Object name" 字段:slugs,数组#["my-object-name"] 结束

其中 slugs 包含一个字符串数组。但是有些是重复的,不应该。

如何构建查询来搜索数组中的重复项?

这是我的实际方法,但它的结果包含我的所有条目,这是不正确的

    results = MyModel.unscoped.collection.aggregate([
       {"$match" => {"count" => {"$gt" => 1}}},
       {'$group' => {"_id" => "$slugs", 
                     "count" => {"$sum" => 1}}}])

有人可以建议我查询吗?

您可以尝试以下聚合。

您需要 $match$group 阶段和 $unwind slugs 之后对每个 slug 元素应用分组。

MyModel.unscoped.collection.aggregate([
       {$unwind => "$slugs"}, 
       {$group => {_id => "$slugs",
            count => {"$sum" => 1}}}, 
       {$match => {count => {"$gt" => 1}}}
])

这将为您提供整个集合中所有重复的 slug 元素。

我的确切查询如下所示:

results = MyModel.unscoped.collection.aggregate(
         [{"$group" => 
                   {_id: {"_slugs" => "$_slugs"},
                    recordIds: {"$addToSet" => "$_id"}, 
                    count: {"$sum" => 1}
                   }
            },
          {"$match" => {count: {"$gt" => 1} } } 
          ])