Mongo 为两个或多个字段的条目查找重复项 [英] Mongo find duplicates for entries for two or more fields

查看:34
本文介绍了Mongo 为两个或多个字段的条目查找重复项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的文件:

{
    "_id" : ObjectId("557eaf444ba222d545c3dffc"),
    "foreing" : ObjectId("538726124ba2222c0c0248ae"),
    "value" : "test",
}

我想查找对 foreing & 具有重复值的所有文档.

I want to find all documents which have duplicated values for pair foreing & value.

推荐答案

您可以通过运行以下聚合管道操作轻松识别重复项:

You can easily identify the duplicates by running the following aggregation pipeline operation:

db.collection.aggregate([
    { 
        "$group": { 
            "_id": { "foreing": "$foreing", "value": "$value" }, 
            "uniqueIds": { "$addToSet": "$_id" },
            "count": { "$sum": 1 } 
        }
    }, 
    { "$match": { "count": { "$gt": 1 } } }
])

$group运算符用于将文档按foreignvalue键值分组,然后创建一个$addToSet 运算符.这为您提供了每个组的唯一表达式值数组.使用 $sum 运算符.

The $group operator in the first step is used to group the documents by the foreign and value key values and then create an array of _id values for each of the grouped documents as the uniqueIds field using the $addToSet operator. This gives you an array of unique expression values for each group. Get the total number of grouped documents to use in the later pipeline stages with the $sum operator.

在第二个管道阶段,使用 $match 运算符过滤掉所有计数为 1 的文档.过滤掉的文档代表唯一的索引键.

In the second pipeline stage, use the $match operator to filter out all documents with a count of 1. The filtered-out documents represent unique index keys.

剩余的文档将是集合中对于 foreing & 具有重复键值的那些文档..

The remaining documents will be those in the collection that have duplicate key values for pair foreing & value.

这篇关于Mongo 为两个或多个字段的条目查找重复项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆