Home > Mobile >  how can I get whole documents of duplicate records in mongodb?
how can I get whole documents of duplicate records in mongodb?

Time:09-09

I am trying to get all fields of document using pymongo. but getting only group by fields. I want all documents with all fields.

collection.aggregate([
  {"$group": {
    "_id": {"des": "$Descreption", "price": "$NewPrice"}, "count": {"$sum": 1}}
  },
  {"$match": {"_id" :{ "$ne" : "null" } , "count" : {"$gt": 1} } },
  {"$project": {"Descreption" : "$_id", "_id" : 0} }
])

CodePudding user response:

You can use $push with $$ROOT for this:

db.collection.aggregate([
  {
    $group: {
      _id: {des: "$Descreption", price: "$NewPrice"},
      count: {$sum: 1},
      data: {$push: "$$ROOT"} // add this line
    }
  },
  {$match: {_id: {$ne: "null"}, count: {$gt: 1}}},
  {$project: {
      Descreption: "$_id",
      data: 1, // add this line
      _id: 0
    }
  }
])

See how it works on the playground example

  • Related