Chinmay Waghmare
Chinmay Waghmare

Reputation: 5456

Mongo Get all the documents within 10 miles of location specified

I have 2 collection ServiceProvider and Parents.

ServiceProvider(_id, ServiceProviderID, ...)

Parents( _id, ID, Location:[ Lat, Long ], ... )

ServiceProviderID of ServiceProvider collections is linked to ID of Parents collections.

I want all the service providers within 10 miles of locations.

So basically I want to join ServiceProvider and Parents collection and list all the ServiceProvider within 10 miles of location.

I have tried the following query:

db.ServiceProvider.aggregate([
   {
        $lookup:
        {
            from: "Parents",
            localField: "ServiceProviderID",
            foreignField: "ID",
            as: "ServiceProviderArr"
        }
   },
   {
      $match: { "ServiceProviderArr": { $ne: [] } }
   }
])

It gives me following result:

{
    "_id" : ObjectId("577cc2ce588aec59178b4567"),
    ...
    "ServiceProviderArr" : [
        {
            "_id" : ObjectId("577cbe33588aecf6168b45c6"),
            "ID" : "193",
            ...
            "Location" : {
                "Lat" : "40.75368539999999",
                "Long" : "-73.9991637"
            }
        }
    ]
}

Upvotes: 1

Views: 159

Answers (1)

sergiuz
sergiuz

Reputation: 5529

If I understand well, this query might be what you need:

db.Parents.aggregate([

   { $geoNear: {
                 near: { type: "Point", coordinates: [ 0, 0 ] },
                 spherical: true,
                 distanceField: "dist.calculatedd",
                 maxDistance: 10
             }
   },
   { $lookup: {
            from: "ServiceProvider",
            localField: "ID",
            foreignField: "ServiceProviderID",
            as: "ServiceProviderArr"
        }
    }
]).pretty()

You need to change your center point coordinates and max distance accordingly

Upvotes: 1

Related Questions