Home  >  Article  >  Backend Development  >  How to do geospatial queries with Mongodb

How to do geospatial queries with Mongodb

小云云
小云云Original
2017-11-25 09:43:411926browse

Mongodb, a distributed document storage database, written in C++ language, aims to provide scalable, high-performance data storage solutions for WEB applications. MongoDB is a high-performance, open source, schema-less document database, which is currently a popular NoSQL database. It can be used to replace traditional relational databases or key/value storage in many scenarios.

In mobile development, positioning functions are often used. For example, apps such as Meituan, Ele.me, Maoyan Movies, etc. all use mobile positioning, and then find some locations near your geographical location. Service Information.

So this article will use Mongodb as the database to describe how to perform positioning queries at the database level.

Analysis

For example, we need to make an app. Merchants can publish their products on the app, and users can open the app to view the products closest to them.

If there is no need for geographical location, it is easy to handle. Just insert the database and check the database directly. However, if geographical location is used, you need to use some location functions of Mongodb.

Mongodb has a geospatial index, which can be used to calculate latitude and longitude. The following continues to introduce how to use this function.

Implementation

The following takes Nodejs+mongoose as an example

Create Schema:

const mongoose = require( 'mongoose' );let goodsSchema = new mongoose.Schema( {
 name: String,
 price: Number,
 location: {
     type: [ Number ],
     index: {
         type: '2dsphere',
         sparse: true
     }
 }
}, {
 collection: 'Goods'} )

Create Model

let goodsModel = mongoose.model ('Goods', goodsSchema)

Insert data

Insert data into the database according to the following data format:

{ "name":"名字", "price":12, "location":[经度,纬度]
}

View data near the user

goodsModel.find( {     'location': {
         $nearSphere: [             parseFloat( 经度 ),             parseFloat( 纬度 )
         ],
         $maxDistance: 1000
     }
 } ).limit(10).skip(0).lean().exec();


The above content is to share with you the usage of location index. It is a very practical function. I hope everyone can apply it.

Related recommendations:

How to make the use of database indexes more efficient?

View the index method of MySQL data table

What is mongoDB database

The above is the detailed content of How to do geospatial queries with Mongodb. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn