MongoDB geolocation Search

Source: Internet
Author: User
LBS, which stores the latitude and longitude coordinates of each location, searches for nearby locations and establishes a geographical index to improve query efficiency.

MongoDB geolocation Index,2d and 2dsphere, corresponds to planar and spherical surfaces.

1. Create lbs collection Storage location coordinates

Use Lbs;db.lbs.insert (    {        loc:{            type: ' point ',            coordinates: [113.332264, 23.156206]        },        Name: "Guangzhou East Station"    }) Db.lbs.insert (    {        loc:{            type: "point",            coordinates: [113.330611, 23.147234]        },        name: "Forest and West"    }) Db.lbs.insert (    {        loc:{            type: "point",            coordinates: [ 113.328095, 23.165376]        },        name: "Balance Stand"    })

2. Create a geo-index
Db.lbs.ensureIndex (    {        loc: "2dsphere"    })

3. Query for nearby coordinates

The current position is: Times Square,

Coordinates:113.323568, 23.146436

Search nearby points within a kilometer, sorted by near to far

Db.lbs.find (    {        loc: {            $near: {                $geometry: {                    type: ' point ',                    coordinates: [113.323568, 23.146436]}                ,                $maxDistance: +}}    )

Search Results:
{"_id": ObjectId ("556a651996f1ac2add8928fa"), "loc": {"type": "Point", "coordinates": [113.330611, 23.147234]}, " Name ":" Forest and West "}

The PHP code is as follows:
 Selectdb ($dbname); } catch (Mongoexception $e) {throw new errorexception (' Unable to connect to DB server. Error: '.    $e->getmessage (), 31); } return $db;}    Insert coordinates to mongodbfunction Add ($dbconn, $tablename, $longitude, $latitude, $name) {$index = array (' loc ' = ' 2dsphere '); $data = Array (' loc ' = = Array (' type ' = = ' point ', ' coordinates ' =    > Array (doubleval ($longitude), Doubleval ($latitude))), ' name ' = = $name);    $coll = $dbconn->selectcollection ($tablename);    $coll->ensureindex ($index);    $result = $coll->insert ($data, Array (' w ' = true)); Return (Isset ($result [' OK ']) &&!empty ($result [' OK '])? True:false;} Search nearby coordinate function query ($dbconn, $tablename, $longitude, $latitude, $maxdistance, $limit =10) {$param = Array (' Loc ' = = Array (' $nearSphere ' = = Array (' $geometry ' = = Array (' type ') =>                ' Point ', ' coordinates ' = = Array (doubleval ($longitude), Doubleval ($latitude)),    ' $maxDistance ' = $maxdistance *1000));    $coll = $dbconn->selectcollection ($tablename);    $cursor = $coll->find ($param);        $cursor = $cursor->limit ($limit);    $result = Array ();    foreach ($cursor as $v) {$result [] = $v; } return $result;} $DB = conn (' localhost ', ' lbs ', ' root ', ' 123456 ');//randomly insert 100 coordinate records for ($i =0; $i <100; $i + +) {$longitude = ' 113.3 '. Mt_rand (    10000, 99999);    $latitude = ' 23.15 '. Mt_rand (1000, 9999);    $name = ' name '. Mt_rand (10000,99999); Add ($db, ' lbs ', $longitude, $latitude, $name);} Search for points within one kilometer $longitude = 113.323568; $latitude = 23.146436; $maxdistance = 1; $result = query ($db, ' lbs ', $longitude, $latitud E, $maxdistance);p Rint_r ($result);? >

To demonstrate PHP code, you first need to create users and execute auth in MongoDB's lbs. Here's how:

Use Lbs;db.createuser (    {        "user": "Root",        "pwd": "123456",        "roles": []    }) Db.auth (    {        " User ":" Root ",        " pwd ":" 123456 "    })

The above describes the MongoDB location search, including the aspects of the content, I hope that the PHP tutorial interested in a friend helpful.

  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.