mongodb 如何查找具有相同字段的mongo文档

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14770170/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 13:02:31  来源:igfitidea点击:

How to find mongo documents with a same field

mongodb

提问by Nikita Platonenko

I have a mongo collection, and I need to find documents in this collection, in wich fields name and adrress are equal.

我有一个 mongo 集合,我需要在这个集合中找到文档,其中名称和地址是相等的。

I have searched a lot, I could only find MongoDb query condition on comparing 2 fieldsand MongoDB: Unique and sparse compound indexes with sparse values, but in these questions they are looking for documents in which field a = field b, but I need to find document1.a == document2.a

我搜索了很多,我只能在比较 2 个字段MongoDB 时找到MongoDb 查询条件:具有稀疏值的唯一和稀疏复合索引,但在这些问题中,他们正在寻找字段 a = 字段 b 中的文档,但我需要找到 document1.a == document2.a

回答by Stennie

You can find duplicates using the Aggregation Frameworkand $group.

您可以使用聚合框架$group.

Example data set up:

示例数据设置:

// Batch insert some test data
db.mycollection.insert([
    {a:1, b:2, c:3},
    {a:1, b:2, c:4},
    {a:0, b:2, c:3},
    {a:3, b:2, c:4}
])

Aggregation query:

聚合查询:

db.mycollection.aggregate(
    { $group: { 
        // Group by fields to match on (a,b)
        _id: { a: "$a", b: "$b" },

        // Count number of matching docs for the group
        count: { $sum:  1 },

        // Save the _id for matching docs
        docs: { $push: "$_id" }
    }},

    // Limit results to duplicates (more than 1 match) 
    { $match: {
        count: { $gt : 1 }
    }}
)

Example output:

示例输出:

{
    "result" : [
        {
            "_id" : {
                "a" : 1,
                "b" : 2
            },
            "count" : 2,
            "docs" : [
                ObjectId("5162b2e7d650a687b2154232"),
                ObjectId("5162b2e7d650a687b2154233")
            ]
        }
    ],
    "ok" : 1
}