Database Reference
In-Depth Information
> db.zips.findOne({zip: 10011})
{
"_id" : ObjectId("4d291187888cec7267e55d24"),
"city" : "New York City",
"loc" : {
"lon" : -73.9996
"lat" : 40.7402,
},
"state" : "New York",
"zip" : 10011
}
In addition to the expected city, state, and ZIP fields, you'll see a fourth field, loc , that
stores the coordinates for the geographic center of the given ZIP code. This is the field
you'll want to index and query on. Only fields containing coordinate values can be
spatially indexed. But note that the form of the fields isn't too strict. You could just as
easily use different keys to represent these coordinates:
{ "loc" : { "x" : -73.9996, "y" : 40.7402 } }
Or you might use a simple array pair:
{ "loc" : [ -73.9996, 40.7402 ] }
As long as you use a sub-document or an array, each of which contains two values, the
field can be spatially indexed.
Now, to create the index itself, you specify 2d as the index type:
> use geo
> db.zips.ensureIndex({loc: '2d'})
This builds a spatial index on the loc field. Only those documents containing a prop-
erly formatted coordinate pair will be indexed; thus spatial indexes are always sparse.
By default, the minimum and maximum coordinate values will be -180 and 180, respec-
tively. This is the proper range for geographic coordinates, but if you happen to be
indexing for a different domain, then you can set the min and max values as follows:
> use games
> db.moves.ensureIndex({loc: '2d'}, {min: 0, max: 64})
Once you've built a spatial index, you can perform spatial queries. 3 The simplest and
most common type of spatial query is known as the $near query. When used in con-
junction with a limit, a $near query allows you to find the n nearest locations to a
given coordinate. For example, to find the three ZIP codes closest to Grand Central
Station, you can issue the following query:
> db.zips.find({'loc': {$near: [ -73.977842, 40.752315 ]}}).limit(3)
{ "_id" : ObjectId("4d291187888cec7267e55d8d"), "city" : "New York City",
"loc" : { "lon" : -73.9768, "lat" : 40.7519 },
"state" : "New York", "zip" : 10168 }
{ "_id" : ObjectId("4d291187888cec7267e55d97"), "city" : "New York City",
3
Note that this contrasts with non-spatial queries, which can be issued with or without a supporting index.
Search WWH ::




Custom Search