Databases Reference
In-Depth Information
You can drop all indexes on a collection by passing in * as the value for the index key:
> db.runCommand({"dropIndexes" : "foo", "index" : "*"})
Another way to delete all indexes is to drop the collection. This will also delete the
index on _id (and all of the documents in the collection). Removing all of the documents
in a collection (with remove ) does not affect the indexes; they will be repopulated when
new documents are inserted.
Geospatial Indexing
There is another type of query that is becoming increasingly common (especially with
the emergence of mobile devices): finding the nearest N things to a current location.
MongoDB provides a special type of index for coordinate plane queries, called a
geospatial index .
Suppose we wanted to find the nearest coffee shop to where we are now, given a latitude
and longitude. We need to create a special index to do this type of query efficiently,
because it needs to search in two dimensions. A geospatial index can be created using
the ensureIndex function, but by passing "2d" as a value instead of 1 or -1:
> db.map.ensureIndex({"gps" : "2d"})
The "gps" key must be some type of pair value, that is, a two-element array or embedded
document with two keys. These would all be valid:
{ "gps" : [ 0, 100 ] }
{ "gps" : { "x" : -30, "y" : 30 } }
{ "gps" : { "latitude" : -180, "longitude" : 180 } }
The keys can be anything; for example, {"gps" : {"foo" : 0, "bar" : 1}} is valid.
By default, geospatial indexing assumes that your values are going to range from -180
to 180 (which is convenient for latitude and longitude). If you are using it for other
values, you can specify what the minimum and maximum values will be as options to
ensureIndex :
> db.star.trek.ensureIndex({"light-years" : "2d"}, {"min" : -1000, "max" : 1000})
This will create a spatial index calibrated for a 2,000 × 2,000 light-year square.
Geospatial queries can be performed in two ways: as a normal query (using find ) or as
a database command. The find approach is similar to performing a nongeospatial
query, except the conditional "$near" is used. It takes an array of the two target values:
> db.map.find({"gps" : {"$near" : [40, -73]}})
This finds all of the documents in the map collection, in order by distance from the
point (40, -73). A default limit of 100 documents is applied if no limit is specified. If
you don't need that many results, you should set a limit to conserve server resources.
For example, the following code returns the 10 nearest documents to (40, -73):
> db.map.find({"gps" : {"$near" : [40, -73]}}).limit(10)
 
Search WWH ::




Custom Search