Clever Use of Mongodb for geographic space query, mongodb geographical space
MongoDB is a distributed file storage-based database. Written in C ++. It is designed to provide scalable, high-performance data storage solutions for WEB applications.
In mobile development, positioning functions are often used, such as Meituan, ELE. Me, and cat-eye movies, then find some services and information near your location.
Geographic location index is a feature that MongoDB has long been well known to users. It adopts the Spherical and Flat modes and provides a wide array of address location representation methods, such as 2d, 2dsphere, and GeoJSON. For mobile apps such as map software, taxi hailing software, and take-out software, MongoDB's powerful geographic location index function makes it the best choice, for IOT, smart city, and other fields, a large number of operations related to geographical locations are also required. These operations are the arena of MongoDB.
This article describes how to locate and query Mongodb databases at the database level.
For example, we need to create an app. Merchants can publish their products to the app, and users can open the app to view their products from near to far.
If you do not need a geographical location, just plug in the database and check the database. However, if you use a geographical location, you need to use some location functions of Mongodb.
Mongodb has a geospatial index that can be used for latitude and longitude computing. The following describes how to use this function.
The following uses Nodejs + mongoose as an example.
1. Create a Schema:
Const mongoose = require ('mongoose ');
Let goodsSchema = new mongoose. Schema ({
Name: String,
Price: Number,
Location :{
Type: [Number],
Index :{
Type: '2dsphere ',
Sparse: true
}
}
},{
Collection: 'goods'
})
2. Create a Model
Let goodsModel = mongoose. model ('goods', goodsSchema)
3. insert data
Insert data to the database in the following format:
{
"Name": "name ",
"Price": 12,
"Location": [longitude, latitude]
}
4. view User Data nearby
GoodsModel. find ({
'Location ':{
$ NearSphere :[
ParseFloat (longitude ),
ParseFloat (latitude)
],
$ MaxDistance: 1000
}
} 2.16.limit(102.16.skip(02.16.lean(cmd.exe c ();
Summary:This article mainly shares the usage of the Location index. It is a very practical function. The demo is not as easy as it is, but the main skeleton is coming out. Thank you!