How to implement the geographical location query function of data in MongoDB
Abstract:
In modern data-driven applications, the geographical location query function has become more and more is becoming more and more important. This article will introduce how to implement the geographical location query function in MongoDB and provide specific code examples.
Introduction:
MongoDB is a full-featured non-relational database that supports geographical location query functions and can use geographical coordinates to index and query data. The geographical location query function is very useful in many application scenarios, such as nearby people, store location, itinerary planning, etc. In this article, we will explore how to implement these features in MongoDB.
{
"name": "ABC store",
"location": [longitude, latitude]
}
The sample code to create a geographical index in MongoDB is as follows:
db.collection.createIndex({ location: "2dsphere" })
db.collection.insert({
"name": "ABC store",
"location": [longitude, latitude]
})
The sample code is as follows:
// Query stores near a given geographical location, limited to within 1000 meters
db.collection.find({
"location ": {
$near: { $geometry: { "type": "Point", "coordinates": [longitude, latitude] }, $maxDistance: 1000 }
}
})
// Query stores nearby a given geographical location, limited to within 1000 meters, and return the distance
db.collection.aggregate ([
{
$geoNear: { near: { "type": "Point", "coordinates": [longitude, latitude] }, distanceField: "distance", maxDistance: 1000, spherical: true }
}
])
Summary:
Using the geographical location query function in MongoDB, we can easily implement various geographical location-related Applications such as nearby people, store location, trip planning, etc. Through the introduction and specific code examples of this article, I believe readers will have a deeper understanding and mastery of implementing the geographical location query function in MongoDB.
The above is the detailed content of How to implement the geographical location query function of data in MongoDB. For more information, please follow other related articles on the PHP Chinese website!