42

私はmongoコレクションを持っていますが、このコレクションで、フィールド名とアドレスが等しいドキュメントを見つける必要があります。

私はたくさん検索しましたが、 2つのフィールドとMongoDBを比較するとMongoDbクエリ条件しか見つかりませんでした:スパース値を持つ一意でスパースな複合インデックスですが、これらの質問では、フィールドa =フィールドbであるドキュメントを探していますが、 document1.a==document2.aを検索します

4

1 に答える 1

117

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
}
于 2013-04-08T12:16:15.050 に答える