1.获取mongodb的连接对象
$mongo = new \MongoDB\Driver\Manager("mongodb://192.168.0.127:27017");
2.插入一个集合
public function createCollection()
{
$mongo = new \MongoDB\Driver\Manager("mongodb://192.168.0.127:27017",array(
'username' =>"admin",
'password' => "123456",
)
);
$writeConcern = new \MongoDB\Driver\WriteConcern(\MongoDB\Driver\WriteConcern::MAJORITY, 1000);
$bulk = new \MongoDB\Driver\BulkWrite;
$document = ['_id' => new \MongoDB\BSON\ObjectID, 'name' => '张三',"age"=>18];
$_id= $bulk->insert($document);
$result = $mongo->executeBulkWrite('local.runoob', $bulk, $writeConcern);
print_r($result);
}
3.查询mongoDb文档
public function find()
{
$manager = new \MongoDB\Driver\Manager("mongodb://192.168.0.127:27017",array(
'username' =>"admin",
'password' => "123456",
)
);
$filter = ['ip' => ['$gt' => "\"192.168.0.124\""]];
$options = [
'sort' => ['createTime' => -1],
"limit"=>5,
];
$query = new \MongoDB\Driver\Query($filter, $options);
$result = $manager->executeQuery('test.user', $query);
$data=[];
$rows=[];
foreach ($result as $v){
$rows[]=json_decode(json_encode($v,JSON_UNESCAPED_UNICODE),true);
}
$data['rows']=$rows;
$data['total']=count($rows);
print_r($data);
}
4.更新文档
public function update()
{
$manager = new \MongoDB\Driver\Manager("mongodb://192.168.0.127:27017",array(
'username' =>"admin",
'password' => "123456",
)
);
$bulk = new \MongoDB\Driver\BulkWrite;
$where=["account"=>89312135258];
$param=['$set'=> ["updateTime"=>date("Y-m-d H:i:s",time())]];
$bulk->update($where,$param);
$writeConcern = new \MongoDB\Driver\WriteConcern(\MongoDB\Driver\WriteConcern::MAJORITY, 1000);
$res = $manager->executeBulkWrite('test.user', $bulk, $writeConcern);
print_r($res);
}
5.删除一个文档
public function del()
{
$manager = new \MongoDB\Driver\Manager("mongodb://192.168.0.127:27017",array(
'username' =>"admin",
'password' => "123456",
)
);
$bulk = new \MongoDB\Driver\BulkWrite;
$bulk->delete(['ip' => "192.168.0.125"]);
$writeConcern = new \MongoDB\Driver\WriteConcern(\MongoDB\Driver\WriteConcern::MAJORITY, 1000);
$res = $manager->executeBulkWrite('test.user', $bulk, $writeConcern);
print_r($res);
}