2013-02-08 28 views
22

我有一个mongo集合,并且我需要在此集合中查找文档,其中的字段名称和地址是平等的。如何找到具有相同字段的mongo文档

我寻觅了很多,我只能找到MongoDb query condition on comparing 2 fieldsMongoDB: Unique and sparse compound indexes with sparse values,但这些问题,他们正在寻找的文件,其中一个场场= B,但我需要找到document1.a == document2.a

+1

你如何理解'document2'是什么?这是找到所有重复的情况吗? – Sammaye

+0

所以你想找到重复的东西? – Philipp

回答

71

您可以使用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 
} 
+2

+1非常感谢(为Mongovue用户删除评论//) – JPBlanc

相关问题