Ryan
Ryan

Reputation: 1

Mongo - Query multiple locations at once

I'm currently trying to find all users who live within any one of a list of locations (this list of locations can be large, so doing multiple queries, than a union on the server-side, isn't necessarily ideal).

The use case, for example, would be to find all users who live within 2 miles of any church in my current city given a list of coordinates for those churches.

Right now, this following location query works:

db.users.count( { location: { $within: { $centerSphere: [ [-84.330984, 33.8615], 2 / 3959  ] } } } )

as well as:

db.users.count( {location : { $near : [ -84.330984 , 33.8615 ] , $maxDistance : 2 / 69 }  })

However, I'd like to be able to count the number of users who live in a range of different locations. i.e. Something like:

db.users.count( { $or: [{ location: { $within: { $centerSphere: [ [-84.330984, 33.8615], 2 / 3959  ] } } },{ location: { $within: { $centerSphere: [ [-85.331122, 34.97832], 2 / 3959  ] } } } ] } )

Right now, when I run this query, Mongo gives the documented error:

Tue Mar 26 17:24:22 uncaught exception: count failed: {
"errmsg" : "exception: $or may not contain 'special' query",
"code" : 13291,
"ok" : 0
}

From this error and the open JIRA ticket (https://jira.mongodb.org/browse/SERVER-3984), Mongo is currently limited from being able to perform multiple location queries using the $or (or $all) operator, so I can't chain location queries.

Is there a best practices or work-around for accomplishing this? Again, I'd prefer not to have a separate query for each location than merge them together; though I realize that may be the only option.

I'm currently using Mongo 2.2.3, but have no issues with upgrading to 2.4 if it will resolve this dilemma.

Thanks

Upvotes: 0

Views: 1980

Answers (1)

Ray
Ray

Reputation: 568

If you are farmiliar with javascript, you can use mapReduce to achieve this.

However, there are two methods ,$near and $centerSphere ,needed to build and you can not perform mapreduce exceeding 1000 records.

Since mongoDB is restricting for $or operator, this is the first idea crossing my mind to solve this.

http://docs.mongodb.org/manual/applications/map-reduce/

Upvotes: 1

Related Questions