I have MongoDb database with collection users containing documents structured as below:
{
firstName: "firstname",
"phone": "123456",
"places":[
{
"name" : "somename",
"address" : "Woollahra, New South Wales, Australia",
"loc" : {
"type" : "Point",
"coordinates" : [
151.23721839999996,
-33.8884085
]
},
"url" : "ttttt2",
"registeredOn" : ISODate("2015-06-17T20:14:10.986Z"),
"id" : ObjectId("5517632982ae879883216fe2b2")
},
{
"name" : "somename",
"address" : "something else, Australia",
"loc" : {
"type" : "Point",
"coordinates" : [
151.23721839999996,
-33.8884085
]
},
"url" : "ttttt2",
"registeredOn" : ISODate("2015-06-17T20:14:10.986Z"),
"id" : ObjectId("5517632982ae879883216fe2b2")
}
]}
Each document has bunch of properties e.g firstName, phone etc. It also has places property that is an array of subdocuments.
Each subdocument has loc property that stores coordinates of the "place" subdocument describes. I basically need to pull out places objects in order of distance from specific location I pass to query.
I cannot figure out how can I run collection.find $near queries to get list of places based on its location. I figured first of all I need to set up 2dsphere index on places.loc and tried:
db.users.createIndex({"places.loc":"2dsphere"})
But I'm getting "errmsg" : "exception: Can't extract geo keys.
Is this even possible with structure I already have in database? If so how would I do it? My documents sample is below, thank you in advance for any help. BTW I'm using NodeJs with native mongoDB driver.
EDIT:
I tried:
db.users.createIndex({"loc":"2dsphere"})
and this result in:
{
"createdCollectionAutomatically" : false,
"numIndexesBefore" : 3,
"numIndexesAfter" : 3,
"note" : "all indexes already exist",
"ok" : 1
}
and that gave me hope but then when I try to run query:
db.users.find({
'places.loc': {
$near: {
$geometry: {
type: "Point",
coordinates: [-73.965355, 40.782865]
},
$maxDistance: 20000
}
}
})
I get this:
Error: error: {
"$err" : "Unable to execute query: error processing query: ns=marankings.users limit=0 skip=0\nTree: GEONEAR field=places.loc maxdist=20000 isNearSphere=0\nSort: {}\nProj: {}\n planner returned error: unable to find index for $geoNear query",
"code" : 17007
}