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

Nik*_*nko 30 mongodb

我有一个mongo集合,我需要在这个集合中找到文件,字段名称和地址相同.

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

Ste*_*nie 90

您可以使用聚合框架$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}
])
Run Code Online (Sandbox Code Playgroud)

聚合查询:

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 }
    }}
)
Run Code Online (Sandbox Code Playgroud)

示例输出:

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

  • +1非常好感谢(对于Mongovue用户删除评论//) (3认同)