【问题标题】:How to find mongo documents with a same field如何查找具有相同字段的mongo文档
【发布时间】:2013-01-24 01:51:15
【问题描述】:

我有一个 mongo 集合,我需要在这个集合中查找文档,其中的字段 name 和 address 是相等的。

我搜索了很多,我只能找到MongoDb query condition on comparing 2 fieldsMongoDB: Unique and sparse compound indexes with sparse values,但是在这些问题中他们正在寻找字段a =字段b的文档,但我需要找到document1.a == document2。一个

【问题讨论】:

  • 您如何理解document2 是什么?是查找所有重复项的情况吗?
  • 所以你想找到重复的?

标签: mongodb


【解决方案1】:

您可以使用Aggregation Framework$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
}

【讨论】:

  • +1 非常感谢(对于 Mongovue 用户删除 cmets //)
  • 嗨@Stennie 我们可以在删除数据库后恢复它吗?还是它的收藏?
  • @Ashh 希望您有一个可以从中恢复的备份(或者可能是延迟的辅助设备?)。删除数据没有“撤消”操作。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-07-14
  • 1970-01-01
  • 1970-01-01
  • 2015-08-29
  • 2015-07-21
  • 1970-01-01
  • 2016-09-26
相关资源
最近更新 更多