MongoDB geospatial search by zip MongoDB geospatial search by zip mongoose mongoose

MongoDB geospatial search by zip


That is not how a Geo-spatial index works or really how the queries should work either. Consider that when you created the index your statement was likely something like this:

db.zipcodes.ensureIndex({ "loc": "2d" })

So you have asked for a 2d index to be created on the "loc" field, which also has the data in the required format for a Geo-Spatial index. That means it's indexing data in the "loc" field.

What you propose to do is somehow provide another field that is not "loc" as part of the query and is therefore irrelevant to the data. That simply cannot work because that data is not in the "loc" field. Essentially this is no different to querying a value for "City" under the "State" field. There is no special magic about field selection in a Geo-Spatial query, just the tools to select a range out of the index.

There is nothing wrong with mixing query forms though, so if you wanted to otherwise filter the results on more detail than just the proximity to a given point you could do something like this:

 db.zipcodes.find({     "loc": {          "$near": [ -87.68, 41.83 ],          "$maxDistance": 5*(1/69)       },       "_id": { "$gte": "60630", "$lte": "60680"}  })

Which will not only find the points nearest to the queried point but would then restrict those results to just those zip codes within the range.

If in fact all you are looking for is that you do not know the point co-ordinates but you do know a "zipcode" then you have two queries to issue in order to get the results.

var zipLoc = db.zipcodes.findOne({ "_id": "60661" })var results = db.zipcodes.find({    "loc": {          "$near": zipLoc.loc,          "$maxDistance": 5*(1/69)       }})

So that is what you would be doing to return results near a certain "zipcode".