在Laravel中使用MongoDB的方法示例(2)

命令行创建MongoDB数据库

macOS中,在命令行执行mongo开启MongoDB Shell

./mongo

使用show dbs查看已有数据库

show dbs;

admin  0.000GB
config  0.000GB
local  0.000GB
viewers 0.000GB

如果没有发现viewers,则创建该数据库。注意只有viewers中存在collection时, 上面结果才会显示viewers

use viewers;

使用数据库后,需要创建colleciton

db.ad_clicks.insert({"ip":"201.35.63.14", "ad_index": 3, "created_at": "2019-06-10 11:34:12"})

使用find查询记录

> db.ad_clicks.find()
{ "_id" : ObjectId("5cf71b34e14620598643d23b"), "ip" : "201.34.46.3", "ad_index" : "2", "created_at" : "2019-06-05 11:34:53" }
{ "_id" : ObjectId("5cf71d3de14620598643d23d"), "ip" : "200.14.145.64", "ad_index" : 1, "created_at" : "2019-06-04 11:11:45" }
{ "_id" : ObjectId("5cf71d3ee14620598643d23e"), "ip" : "200.14.145.64", "ad_index" : 1, "created_at" : "2019-06-04 11:11:45" }
{ "_id" : ObjectId("5cf71d44e14620598643d23f"), "ip" : "200.14.145.64", "ad_index" : 1, "created_at" : "2019-06-04 11:11:45" }
{ "_id" : ObjectId("5cf71d45e14620598643d240"), "ip" : "200.14.145.64", "ad_index" : 1, "created_at" : "2019-06-04 12:34:12" }
{ "_id" : ObjectId("5cfe28823316506991c41786"), "ip" : "201.35.63.14", "ad_index" : 3, "created_at" : "2019-06-10 11:34:12" }

在Laravel DB中查询MongoDB

使用了Laravel-MongoDB扩展,可以基于Eloquent与Query Builder操作MySQL一样的数据php artisan thinker

查询ad_clicks集合所有记录

DB::connection('mongodb')->table('ad_clicks')->get()

查询单个记录

DB::connection('mongodb')->collection('ad_clicks')->find('5cf71b34e14620598643d23b')

修改某个记录

DB::connection('mongodb')->collection('ad_clicks')->where('_id', '5cf71b34e14620598643d23b')->update(['ad_index'=>2]);

在Laravel ORM中查询MongoDB

在项目中,创建一个Model

php artisan make:model Models/AdClick

修改继承父类和数据库连接,AdClick.php

...
use Jenssegers\Mongodb\Eloquent\Model;

class AdClick extends Model
{
  protected $connection = 'mongodb';
 
   /**
   * The attributes that are mass assignable.
   *
   * @var array
   */
  protected $fillable = [];

  /**
   * The attributes that aren't mass assignable.
   *
   * @var array
   */
  protected $guarded = [];
}


      

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.heiqu.com/1950.html