Home > Software engineering >  MongoDB: query greater than value of x by a specfic value
MongoDB: query greater than value of x by a specfic value

Time:10-23

I have a MongoDB database with documents representing locations on a map, the document structure is below.

I'am trying to query for documents with sw_x and sw_y value that is 1000 more or 1000 less than the value of the user location which i get from another post request.

This is my get request:

router.get('/getdata', (req, res) =>{
        mongoose.connect(url, function(err, db) {
            if (err) throw err;
            db.collection("mArGo").find({}).toArray(function(err, result) {
              if (err) throw err;
              console.log(result);
              db.close();
            });
          })    
       })

Currently this returns all documents in the database, i just need to figure out how to filter them.

So in other words i need my query to return docs with sw_x, sw_y values that are greater than or less than the user location value by 1000

DB document example:

{
    _id: new ObjectId("6172a1dcb5ce25759cd9506b"),
    epsg: 25832,
    filename: 'dom_657000_5354000_500.sfb',
    offset_x: -650000,
    offset_y: -5360000,
    size_x: 500,
    size_y: 500,
    x_sw: 657000,
    y_sw: 5354000
  }

CodePudding user response:

In the code, you can calculate min, max of x_sw and y_sw and pass it to query:

db.collection.find({
  x_sw: { $gt: 656000, $lt: 658000 },
  y_sw: { $gt: 5353000, $lt: 5355000 }
})
  • Related