heaks
heaks

Reputation: 77

MongoDB Find documents which have duplicate propety values

For example we have a collection of polygons, every documents contains property coordinates

coordinates: [
  {
    lat: 63.23598239
    lng: 37.94858921
  },
  {...}
]

How can we find all documents which have this property duplicated in collection. We need to find 2 or more documents which have the same coordinates array.

Upvotes: 1

Views: 60

Answers (1)

felix
felix

Reputation: 9285

you can achieve this using aggregation like this :

db.test.aggregate([  
   {  
      $group:{  
         _id:"$coordinates",
         sum: {  
            $sum:1
         }, 
         listId: { 
            $push: "$_id"
         }
      }
   },
   {  
      $match:{  
         sum:{  
            $gte:2
         }
      }
   }
])

it will output all duplicates documents, for example :

{ "_id" : [ { "lat" : 63.23598239, "lng" : 37.94858921 } ], "sum" : 4, "listId": [1, 2, 3, 4] }

Upvotes: 1

Related Questions