2013-02-08 15 views
22

私はmongoコレクションを持っています。このコレクションでフィールド名と住所が等しいドキュメントを探す必要があります。同じフィールドを持つmongoドキュメントの検索方法

私は多くのことを検索しました、私だけMongoDb query condition on comparing 2 fieldsMongoDB: Unique and sparse compound indexes with sparse valuesを見つけることができるが、これらの質問に、彼らはフィールドA =フィールド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

関連する問題