1、写入数据
public function mongoConnect()
{
$manager = new \MongoDB\Driver\Manager("mongodb://localhost:27017");
// 准备写入数据
$document1 = [
[
'id' => '1',
'username' => 'zhangsan',
'phone' => '123456'
],
[
'id' => '2',
'username' => 'lisi',
'phone' => '123456'
],
[
'id' => '3',
'username' => 'wangwu',
'phone' => '123456'
],
[
'id' => '4',
'username' => '小红',
'phone' => '123456'
],
[
'id' => '5',
'username' => '小明',
'phone' => '123456'
],
[
'id' => '6',
'username' => '小兰',
'phone' => '123456'
],
[
'id' => '7',
'username' => '小美',
'phone' => '123456'
],
];
// 创建一个批量处理对象
$bulk = new \MongoDB\Driver\BulkWrite;
foreach ($document1 as $key => $value) {
//向写入对象
$bulk->insert($value);
}
//执行写入对象
$result = $manager->executeBulkWrite('taobao.prices', $bulk);
dump($result);
}
2、访问该控制器,返回
3、读取数据
public function mongoConnect()
{
$manager = new \MongoDB\Driver\Manager("mongodb://localhost:27017");
//查询
$query = new \MongoDB\Driver\Query([]);
$rows = $manager->executeQuery('taobao.prices', $query); // 也可选择优先从从库读
foreach ($rows as $r) {
dump($r);
}
}
4、查询结果
5、修改
public function mongoConnect()
{
$manager = new \MongoDB\Driver\Manager("mongodb://localhost:27017");
//修改
$bulk = new \MongoDB\Driver\BulkWrite;
$bulk->update(['username'=>'小明'], [ '$set' => ['phone'=>'888888']]);
$result = $manager->executeBulkWrite('taobao.prices',$bulk);
dump($result);
}
需要注意的是,修改的时候,需要用[‘$set’=>[‘字段名’=>‘字段值’]],不能直接使用[‘字段值’=>‘字段值’]
6、修改之后的结果