Reputation: 81
I have the below document in a collection
{
"_id" : ObjectId("589550ae930b4acade1e2157"),
"itemId" : "2",
"loc" : {
"type" : "GeometryCollection",
"geometries" : [
{
"type" : "Point",
"coordinates" : [
-121.9771985,
37.5637936
],
"address" : "Athy St"
},
{
"type" : "Point",
"coordinates" : [
-121.9430202,
37.3972994
],
"address" : "River Side Ct"
}
]
}
I am using the below query to find the item from the nearest location:
db.store.find(
{
loc:
{ $near :
{
$geometry: { type: "Point", coordinates: [-121.9777269,37.5607686] },
$maxDistance: 3.0 * 1609.34
}
}
}
)
I am trying to restrict to fetch and display only the nearest matching address. Suppose if the queried location matches only River Side ct, I don't want to return Athy Street. This is geometry collection array. I tried to use projections but didn't work.
Can you please let me know how to restrict that? Any help is really appreciated.
Thanks in advance.
Maddy
Upvotes: 1
Views: 92
Reputation: 172
The MongoDB $near
operation sorts by distance (nearest to farthest,
as mentioned in the documentation), so all you will have to do is limit the results.
db.store.find(
{
loc:
{ $near :
{
$geometry: { type: "Point", coordinates: [-121.9777269,37.5607686] },
$maxDistance: 3.0 * 1609.34
}
}
}
).limit(1)
Upvotes: 1