ABDELJALIL AIT ETALEB
ABDELJALIL AIT ETALEB

Reputation: 146

Filter large collection with an efficient way

I m Working on an app like uber , I have a collection of drivers , with currentPosition { latitude , longitutde }

And i want to get the drivers far by 200m , the way i did it is like this on the model :

driverSchema.methods.CloseDriver = function (userCurrentPosition,next) {
  try {    
    const distance = geolib.getPreciseDistance(
      userCurrentPosition,
      this.currentPosition
   );
   return distance <= 200
  } catch (error) {
      return next();
  }
}

and then with a post request with currentPosition of the user on it

     const parsedBody = Object.setPrototypeOf(req.body, {});

      if(parsedBody.hasOwnProperty("latitude") && parsedBody.hasOwnProperty("longitude")){
        const { latitude , longitude } = req.body
        const currentPosition = { latitude , longitude }
        const drivers = await Driver.find({})
        const eligibleDrivers =  drivers.filter((driver)=> driver.CloseDriver(currentPosition))
        return res.status(200).json({
          status : 200 , 
          eligibleDrivers
        });

if we have large array of drivers that would not be very efficient if there is another way to this?

Upvotes: 0

Views: 48

Answers (1)

Sarfraaz talat
Sarfraaz talat

Reputation: 635

You can use $geoNear with aggregate to achieve this from your query itself & not loading all the drivers & then doing this filter in javascript

See this code

db.drivers.aggregate([
   {
     $geoNear: {
        near: { type: "Point", coordinates: [ CurrentLongitude, CurrentLatitude ] },
        distanceField: "distance",
        maxDistance: 2,
        includeLocs: "currentPosition",
        spherical: true
     }
   }
]);

You'd have to store currentPosition latlang of drivers in your schema like this

"currentPosition": {
      "type" : "Point",
      "coordinates" : [ -73.9375, 40.8303 ]
   },

Upvotes: 1

Related Questions