Skip to content

Instantly share code, notes, and snippets.

@sindbach
Created May 5, 2017 04:59
Show Gist options
  • Save sindbach/973e152d1974dcd8fd65fdee70a41d0a to your computer and use it in GitHub Desktop.
Save sindbach/973e152d1974dcd8fd65fdee70a41d0a to your computer and use it in GitHub Desktop.
A simple JS test to show the difference between $nearSphere and $near
(function() {
"use strict";
let coll = db.geomap_tests;
coll.drop();
coll.insert({ _id: "Westfield London", location: [ -0.22157, 51.507176 ] });
coll.insert({ _id: "Green Lanes Shopping Centre", location: [ -0.098092, 51.576198 ] });
print("INDEX: 2dsphere QUERY: GeoJSON");
coll.createIndex({"location": "2dsphere"});
let result = coll.find({"location":{"$nearSphere":{"$geometry":{"type":"Point", "coordinates":[ -0.127748, 51.507333 ] }}}}, {_id:1});
printjson(result.toArray());
result = coll.find({"location":{"$near":{"$geometry":{"type":"Point", "coordinates":[ -0.127748, 51.507333 ]}}}}, {_id:1});
printjson(result.toArray());
/*
print("INDEX: 2dsphere QUERY: legacy");
Querying using legacy coordinates in 2dsphere index is not allowed.
*/
coll.dropIndexes();
coll.createIndex({"location": "2d"});
print("INDEX: 2d QUERY: legacy");
result = coll.find({"location":{"$nearSphere":[ -0.127748, 51.507333 ]}}, {_id:1});
printjson(result.toArray());
result = coll.find({"location":{"$near":[ -0.127748, 51.507333 ]}}, {_id:1});
printjson(result.toArray());
/*
print("INDEX: 2d QUERY: GeoJSON");
Querying using GeoJSON in 2d index is not allowed.
*/
print("");
}());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment