Search code examples
node.jsmongodbmongoosemongodb-querynosql

Mongodb query to find document matching a particular range


I have a problem in which I am getting distance between two geolocations. I have a MongoDB collection in which I have documents that have min_distance, max_distance, and price. I need a query to fetch the price for the distance that I have calculated. Below is my mongodb collection


Solution

  • Try this one:

    distance = 15    
    db.collection.find({
       min_distance: { $lt: distance },
       max_distance: { $gt: distance }
    })
    

    Or you can use expression:

    db.collection.find({
       $expr: {
          $and: [
             { $gt: ["$min_distance", distance] },
             { $lt: ["$max_distance", distance] }
          ]
       }
    })
    

    Mongo Playground