MongoDB $near returns duplicate records

246 views Asked by At
Event Schema:
    Name:String,
    Description: String,
    Location:[
          ll:[long,lat]
          type: String (source,destination)
    ],
    CreatedDate:Date,
    UpdatedDate:Date,

Example of a document:

 {
   Name : 'Test1',
   Description : 'Test1',
   Location:[{
         ll:[{long:-118.2436849,lat:34.0522342}],
         type: 'source'
   },{
         ll:[{long:2,lat:4}],
         type: 'destination'
   }] 
}

I have 7 documents having the same structure as above.

When I make a query :

 db.events.count({'location.ll' : {$near:[-118.2436849,34.0522342]},'location.type':'source'});

I get 14 count back. I should ideally get 7 records but I am getting 14 records. I am not sure what I am doing wrong.

I have already indexed the field "location.ll" as "2d"

Please let me know what am I doing wrong?

Thank you for the help

1

There are 1 answers

4
Felix Yan On BEST ANSWER

This is a documented "feature", and you can get around it by following the suggestions:

For documents with multiple coordinate values, queries may return the same document multiple times if more than one indexed coordinate pair satisfies the query constraints. Use the uniqueDocs parameter to geoNear or the $uniqueDocs operator with $geoWithin.