Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB geospatial query with $not

I have a basic geospatial query working well in MongoDB. It seems that it should be easy to apply $not to get the complement... but it's not working for me. Is it simple user error? Or can MongoDB not handle this query conceptually? I could not find any such limitation in the documentation.

Working query (correctly finds the 2 cities within 10 miles of the center):

db.customers.find({ "location" : { $within : { $center : [[-117.15,32.72],0.15] } } })

Attempted complement query (desired result is the 1 city that is not within 10 miles):

db.customers.find({ "location" : { $not : { $within : { $center : [[-117.15,32.72],0.15] } } } })
error: {
    "$err" : "missing geo field (location) in : {location: { $not: { $within: { $center: [ [ -117.15, 32.72 ], 0.15 ] } } } }",
    "code" : 13042
}

For anyone that wants to copy/paste the query to see the error, here's a tiny bit of sample data:

db.customers.ensureIndex( { "location" : "2d" } )
db.customers.save({"city":"La Mesa","state":"CA","location":[ -117.02,32.76 ]})
db.customers.save({"city":"Chula Vista","state":"CA","location":[ -117.08,32.63 ]})
db.customers.save({"city":"Mexico City","state":"Mexico","location":[-99.133244,19.4326]})

(I'm using MongoDB 1.8.2 in case that matters.)

like image 600
mdahlman Avatar asked Nov 14 '11 18:11

mdahlman


1 Answers

I think this is not possible. As far as I know, location queries will give you a special cursor that can only use location queries as parameters (such as $within).

v. 2.0.1 gives a more descriptive error message: error: { "$err" : "geo field only has 1 element", "code" : 13068 }

The issue with indexing is that, in general, negation is EVIL. Most indexes don't cope well when you turn them around, so even if your query worked, it's probably not desirable because it will probably have to do a table scan.

I'm not entirely sure about this, a message to the newsgroup is probably a good idea.

like image 89
mnemosyn Avatar answered Oct 14 '22 17:10

mnemosyn