Josh Newham
Josh Newham

Reputation: 47

Node JS Mongo $near not working with nested field

I've been working on a simple search using the $near operator but have recently changed my data so the 2dsphere location index is now in the nested field properties.location instead of just location. I am using the Node JS mongo driver and the search worked fine when the index was not nested inside the properties object using the following query, but returns nothing now:

Previous working query:

dbObject.collection("scrapedTimes").find({
            location: {
                $near: {
                    $geometry: {
                        type: "Point" ,
                        coordinates: [lngBound, latBound]
                    },
                    $minDistance: 0,
                    $maxDistance: 100000
                }
            }

})

Current query that returns nothing:

dbObject.collection("scrapedTimes").find({
            "properties.location": {
                $near: {
                    $geometry: {
                        type: "Point" ,
                        coordinates: [lngBound, latBound]
                    },
                    $minDistance: 0,
                    $maxDistance: 100000
                }
            }

})

I have executed this same nested query in Mongo Compass and it seems to work fine so I think it might be a problem with the Node JS driver? I'm quite new to Mongo so there might be something obvious I'm missing here but I just can't get Node to return any results...

Thanks for your time and suggestions,

Josh

DB layout 2dsphere index

Upvotes: 0

Views: 411

Answers (1)

bloo
bloo

Reputation: 1560

Change $near to $nearSphere, there's a difference between the two which mainly relates to calculations using spherical geometry. $near will use flat geometry and won't work because of the 2dSphere index on the nested document.

Check this out for the difference between the two...

In Mongo what is the difference between $near and $nearSphere?

Upvotes: 2

Related Questions