安装
composer require mongodb/mongodb
composer require jenssegers/mongodb
mongodb可视化工具:MongoDBCompass 下载地址
php-ext 下载地址
laravel配置:
/config/app.php
Jenssegers\Mongodb\MongodbServiceProvider::class,
/config/database.php
'mongodb' => [
'driver' => 'mongodb',
'host' => env('MONGODB_HOST', '127.0.0.1'),
'port' => env('MONGODB_POST', '27017'),
'database' => env('MONGODB_DB', 'db1'),
'username' => env('MONGODB_USER', ''),
'password' => env('MONGODB_PASSWORD', ''),
],
模型配置:
<?php
namespace App\Models;
use Jenssegers\Mongodb\Eloquent\HybridRelations;
use Jenssegers\Mongodb\Eloquent\Model as Eloquent;
class Location extends Eloquent
{
use HybridRelations;
protected $connection = 'mongodb'; //库名
protected $collection = 'location'; //文档名
protected $primaryKey = '_id'; //设置id
protected $fillable = ['id', 'lng', 'lat']; //设置字段白名单
}
插入数据代码:
$insert2 = Location::query()->insert(['id' => "1","name"=>"大坪","location"=>[
"type"=>"Point",
"coordinates"=>[
113.92024040222180,22.548708470991890
]
]]);
查询代码:
$users = Location::query()->where('location', 'near', [
'$geometry' => [
'type' => 'Point',
'coordinates' => [
113.92024040222168,
22.548708470991805,
],
],
'$maxDistance' => 50,
])->where("name","like","%大%")->get(["name"]);