Let's see how we can build the geospatial index on a MongoDB collection:
1. Launch the
mongo
interactive shell. Switch to a new database namespace calledgeolocation:
$ ./mongodb/bin/mongo MongoDB shell version: 1.8.1 connecting to: test > use geolocation switched to db geolocation >
2. Insert a few documents in a collection named
map
. Each document must contain an embedded document with two fields, latitude and longitude:> db.map.insert({coordinate: {latitude:23.2342987, longitude:90.20348}}) > db.map.insert({coordinate: {latitude:23.3459835, longitude:90.92348}}) > db.map.insert({coordinate: {latitude:23.6743521, longitude:90.30458}})
3. Create the geospatial index for the
map
collection by issuing the following command:>db.map.ensureIndex({coordinate: '2d'})
4. Enter the next command to check if the index was created:
> db.system.indexes.find() { "name" : "_id_", "ns" : "geolocation.map", "key" : { "_id" : 1 }, "v" ...