mongodbcoordinateshaversine

Find documents in mongoDB collection by coordinates via haversine formula


I have this structure in my collection

{
    "categorie" : "Introduction",
    "quart" : "jour",
    "pdq" : 23,
    "x" : 302375.197993,
    "y" : 5046522.11601,
    "lat" : 45.5586064034326,
    "long" : -73.5310596776929,
    "date" : ISODate("2015-01-01T00:00:00Z"),
}

I have latitude=42.5232886&longitude=-71.5923142 in query parameters. I need to find all documents which are located at less than 3KM from the a coordinate point passed in parameter.

I am using MongoDB 3.6


Solution

  • Actually we don't need Haversine formula in Mongodb.Here I have done with mongoose. We need to create a schema that contain type and coordinates. You can see more details in https://mongoosejs.com/docs/geojson.html

    So it's has another problem with mongoose version. Mongoose v6.3.0 worked for me. When you will use countDocuments with the query, it can be generate error but count function not generating any error. I know count deprecated, it shouldn't be use but I haven't find better solution. If anyone find solution for count, let me know. Also you can visit https://github.com/Automattic/mongoose/issues/6981

    const schema = new mongoose.Schema(
      {
        location: {
          type: {
            type: String,
            enum: ["Point"],
          },
          coordinates: {
            type: [Number],
            index: "2dsphere",
          },
        },
      },
      { timestamps: true }
    );
    
    const MyModel = mongoose.model("rent", schema);

    The query will be

    const result = await MyModel.find({
          location: {
            $near: {
              $geometry: {
                type: "Point",
                coordinates: [Number(filters.longitude), Number(filters.latitude)],
              },
              $maxDistance: filters.maxRadius * 1000,
              $minDistance: filters.minRadius * 1000,
    
            },
          },
        })