How to find mongo documents with a same field

后端 未结 1 1410
走了就别回头了
走了就别回头了 2021-01-30 10:56

I have a mongo collection, and I need to find documents in this collection, in which fields name and address are equal.

I have searched a lot, I could only find MongoDb q

1条回答
  •  有刺的猬
    2021-01-30 11:31

    You can find duplicates using the Aggregation Framework and $group.

    Example data set up:

    // 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}
    ])
    

    Aggregation query:

    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 }
        }}
    )
    

    Example output:

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

    0 讨论(0)
提交回复
热议问题