I want to use MongoDB to search for documents by location information.

Asked 2 years ago, Updated 2 years ago, 90 views

I use MongoDB through Mongoose in Node.js.Think about the data that has the location information on the screen.

{
  location: {
    x —Number,
    y —Number
  }
}

You have defined a schema called .Therefore, I would like to write a code that retrieves data within a certain distance from a given point.Therefore, I think I have to calculate the value of (x-x_0)^2+(y-y_0)^2 and pass the conditions according to its size, but I don't know what to do. In SQL

SELECT* FROM 'locations' WHERE(x-x_0)^2+(y-y_0)^2<radius^2

I want to do something like that.Please let me know if you know.Thank you for your cooperation.

node.js mongodb

2022-09-30 19:34

2 Answers

When searching for location and coordinate information, it is recommended to use the Geospatial Index that MongoDB supports by default.

In this case, it is not spherical coordinates such as latitude and longitude, so you can use 2d Index.

The following is an example of running on mongo shell.

 // Set the location key to 2d Index in the points collection
db.points.ensureIndex(
  { location: '2d'},
  { min: {'x':0, 'y':0}, max: {'x':100, 'y':100}}
);

// Generate test data
for(var x=0;x<100;++x){
  for(vary=0;y<100;++y){
    // Just save it normally
    db.points.save({location:{x:x,y:y}});
  }
}

// search processing
db.points.find({
  location: {
    // Find data within 3 distances from {x:30, y:70}
    $geoWithin: {
      $center: [{x:30, y:70}, 3]
    }
  }
});

In the above example, you can search at a distance (circle range) from a point, but you can also search within a square or polygon range.For more information, see the MongoDB documentation: Query a 2d Index.


2022-09-30 19:34

2d index allows you to search by geoNear.


2022-09-30 19:34

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.