链接mongo
$config = array(
'username' => 'admin',
'password' => '123456'
);
$manager = new \MongoDB\Driver\Manager('mongodb://127.0.0.1:27017',$config);
$writeConcern = new \MongoDB\Driver\WriteConcern(\MongoDB\Driver\WriteConcern::MAJORITY, 1000);
$bulk = new \MongoDB\Driver\BulkWrite();
插入数据
$bulk->insert(['_id' => 1, 'name'=>'张三', 'age' => '12']);
$bulk->insert(['_id' => 2, 'name'=>'李四', 'age' => '16']);
$bulk->insert(['_id' => 3, 'name'=>'王五', 'age' => '18']);
$bulk->insert(['_id' => 4, 'name'=>'张三-01', 'age' => '22']);
$bulk->insert(['_id' => 5, 'name'=>'李四-02', 'age' => '23']);
$bulk->insert(['_id' => 6, 'name'=>'王五-04', 'age' => '32']);
$result = $manager->executeBulkWrite('test.user', $bulk, $writeConcern);
获取数据
$filter = ['_id'=>['$gt'=>2]];
$filter = ['_id'=>['$gt'=>2,'$lt'=>6]];
$filter = ['name'=>['$regex'=>'^李']];
$filter = ['name'=>['$regex'=>'李']];
$filter = ['age'=>['$in'=>["16","12"]]];
$filter = ['age'=>['$nin'=>["16","12"]]];
$options = [
'skip'=>0,
'limit'=>5,
'sort' => ['_id' => -1],
'projection'=>['age'=>false],
];
$query = new \MongoDB\Driver\Query($filter,$options);
$list = $manager->executeQuery('test.user', $query)->toArray();
print_r($list);
根据条件获取某个集合数据条数
$filter = [];
$command = new \MongoDB\Driver\Command(["count"=>"user","query"=>$filter]);
$count = $manager->executeCommand('test',$command)->toArray()[0]->n;
var_dump($count);
更新数据
$filter = ['_id'=>2];
$newObj = ['$set'=>['age'=>'16']];
$updateOptions = ['multi' => false, 'upsert' => false];
$bulk->update($filter, $newObj, $updateOptions);
$result = $manager->executeBulkWrite('test.user', $bulk, $writeConcern);
var_dump($result);
删除某个文档的某个属性
$filter = ['_id'=>2];
$newObj = ['$unset'=>['age'=>1]];
$updateOptions = ['multi' => false, 'upsert' => false];
$bulk->update($filter, $newObj, $updateOptions);
$result = $manager->executeBulkWrite('test.user', $bulk, $writeConcern);
var_dump($result);
删除记录
$filter = ['age'=>'12'];
$deleteOptions = ['limit'=>0];
$bulk->delete($filter, $deleteOptions);
$result = $manager->executeBulkWrite('test.user', $bulk, $writeConcern);
var_dump($result);
自增
$filter = ['_id' => 2];
$newObj = ['$inc' => ['age' => 2]];
$updateOptions = ['multi' => false, 'upsert' => false];
$bulk->update($filter, $newObj, $updateOptions);
$result = $manager->executeBulkWrite('test.user', $bulk, $writeConcern);
var_dump($result);
自减
$filter = ['_id' => 2];
$newObj = ['$inc' => ['age' => -5]];
$updateOptions = ['multi' => false, 'upsert' => false];
$bulk->update($filter, $newObj, $updateOptions);
$result = $manager->executeBulkWrite('test.user', $bulk, $writeConcern);
var_dump($result);
|