如何查找具有相同字段的mongo文档 [英] How to find mongo documents with a same field

查看:92
本文介绍了如何查找具有相同字段的mongo文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个mongo集合,我需要在该集合中查找文档,其中"name"和"adrress"相等.

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

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

I have searched a lot, I could only find MongoDb query condition on comparing 2 fields and 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

推荐答案

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

You can find duplicates using the Aggregation Framework and $group.

数据示例设置:

// 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}
])

汇总查询:

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 }
    }}
)

示例输出:

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

这篇关于如何查找具有相同字段的mongo文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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