Last active
August 29, 2015 14:01
-
-
Save pori/c07aa7453cfd831772ae to your computer and use it in GitHub Desktop.
A simple script demonstrating MongoDB's geospatial index support
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Example used for "Geographic Data with MongoDB" article at Orlando Data Science. | |
* Url: http://orlandods.com/geo-locational-data-mongodb/ | |
* Author: Pori | |
*/ | |
var db = new Mongo().getDB('geodb'); | |
db.places.drop(); // Remove leftover points from previous examples. | |
db.places.ensureIndex({ loc: '2dsphere' }); // Create a geospatial index for a 2D sphere. | |
// Insert our examples into the collection! | |
db.places.insert({ loc: { type: 'Point', coordinates: [2, 2] }}); | |
db.places.insert({ loc: { type: 'Point', coordinates: [1, 3] }}); | |
db.places.insert({ loc: { type: 'Point', coordinates: [6, 7] }}); | |
db.places.insert({ loc: { type: 'Point', coordinates: [9, 11] }}); | |
db.places.insert({ loc: { type: 'Point', coordinates: [3, 6] }}); | |
db.places.insert({ loc: { type: 'Point', coordinates: [7, 9] }}); | |
var box = { type: 'Polygon', coordinates: [[ [0, 0], [3, 0], [3, 3], [0, 3], [0, 0] ]] }; // A geometric figure (box) for detecting the points. | |
var generalRegion = db.places.find({ loc: { $geoWithin: { $geometry: box }}}); // Search for all points within the bounds of the defined box. | |
print('\nPoints within the box:\n'); | |
generalRegion.forEach(function(doc) { print(tojson(doc)); }); // Loop through and print the results. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment