Mongo find duplicates for entries for two or more fields

前端 未结 2 694
孤街浪徒
孤街浪徒 2020-12-28 14:52

I have documents like this:

{
    \"_id\" : ObjectId(\"557eaf444ba222d545c3dffc\"),
    \"foreing\" : ObjectId(\"538726124ba2222c0c0248ae\"),
    \"value\" :         


        
2条回答
  •  悲哀的现实
    2020-12-28 15:29

    We only have to group on the bases of 2 keys, and select the elements with count greater than 1, to find the duplicates.

    Query :- Will be like

    db.mycollection.aggregate(
        { $group: { 
            _id: { foreing: "$foreing", value: "$value" },
            count: { $sum:  1 },
            docs: { $push: "$_id" }
        }},
        { $match: {
            count: { $gt : 1 }
        }}
    )
    

    OUTPUT :- Will be like

    {
        "result" : [
            {
                "_id" : {
                    "foreing" : 1,
                    "value" : 2
                },
                "count" : 2,
                "docs" : [
                    ObjectId("34567887654345678987"),
                    ObjectId("34567887654345678987")
                ]
            }
        ],
        "ok" : 1
    }
    

    Reference Link :- How to find mongo documents with a same field

提交回复
热议问题