Reputation: 2495
I have a collection called "stops" that stores some coordinate info. I used MongoDB 2dsphere index for searching places. For example, I want to query all the stops around a certain position using db.runCommand
:
db.runCommand({
geoNear: "stops",
near: { type: "Point" , coordinates: [ -123.115115, 49.209659 ] },
spherical: true,
minDistance: 0,
maxDistance: 200,
})
The result is an json array:
{
"waitedMS" : NumberLong(0),
"results" : [
{
"dis" : 79.0147493688595,
"obj" : {
"_id" : ObjectId("57e2349b9d0263463a3e93aa"),
"zone_id" : "ZN 99",
"coordinate" : [
-123.116116,
49.209383
],
"stop_id" : 11252,
"stop_code" : 61338,
"stop_url" : "",
"stop_desc" : "MARINE DRIVE STATION LOOP @ BAY 2",
"stop_name" : "MARINE DRIVE STN BAY 2",
"location_type" : 0,
"parent_station" : ""
}
},
{
"dis" : 140.73823410181,
"obj" : {
"_id" : ObjectId("57e2349b9d0263463a3eaec9"),
"zone_id" : "ZN 1",
"coordinate" : [
-123.117038,
49.209801
],
"stop_id" : 11286,
"stop_code" : "",
"stop_url" : "",
"stop_desc" : "SKYTRAIN @ MARINE DRIVE STN",
"stop_name" : "MARINE DRIVE STATION",
"location_type" : 0,
"parent_station" : ""
}
}
],
"stats" : {
"nscanned" : 14,
"objectsLoaded" : 2,
"avgDistance" : 123.782109714949,
"maxDistance" : 140.73823410181,
"time" : 1
},
"ok" : 1.0
}
I am wondering can we do a nested runCommand to further filter the result to be like
{"results" : [
{
"dis" : 79.0147493688595,
"obj" : {
"coordinate" : [
-123.116116,
49.209383
],
"stop_id" : 11252,
"stop_code" : 61338,
"stop_desc" : "MARINE DRIVE STATION LOOP @ BAY 2",
"stop_name" : "MARINE DRIVE STN BAY 2",
}
},
{
"dis" : 140.73823410181,
"obj" : {
"coordinate" : [
-123.117038,
49.209801
],
"stop_id" : 11286,
"stop_code" : "",
"stop_desc" : "SKYTRAIN @ MARINE DRIVE STN",
"stop_name" : "MARINE DRIVE STATION",
}
}
]
}
There is a lot of useless info in original json response.
Upvotes: 0
Views: 430
Reputation: 2285
Use aggregate
instead of runCommand
. It would be like:
db.stops.aggregate([{
$geoNear: {
near: { type: "Point", coordinates: [-123.115115, 49.209659] },
spherical: true,
minDistance: 0,
maxDistance: 200,
distanceField: 'someDistanceFieldProperty'
}
}]);
Take a look at the docs for you to go further: https://docs.mongodb.com/manual/reference/operator/aggregation/geoNear/
Upvotes: 1