增
可以存储数组,分清是什么数据类型的,手动添加_id,重复_id会保存
$manager = new MongoDB\Driver\Manager("mongodb://localhost:27017");
$bulk = new MongoDB\Driver\BulkWrite;
$document = ['id' => 1, 'title' => '222222', 'array' => array('id' => 1, 'tpere' => '不是')];
$_id = $bulk->insert($document);
$writeConcern = new MongoDB\Driver\WriteConcern(MongoDB\Driver\WriteConcern::MAJORITY, 1000);
$result = $manager->executeBulkWrite('test.runoob', $bulk, $writeConcern);
删
删除看清楚参数
$manager = new MongoDB\Driver\Manager("mongodb://localhost:27017");
//创建一个BulkWrite对象
$bulk = new \MongoDB\Driver\BulkWrite();
//limit为1时,删除第一条匹配的数据/为0时,删除所有匹配数据
$bulk->delete(['cid' => '3333'], ['limit' => 1]);
$writeConcern = new MongoDB\Driver\WriteConcern(MongoDB\Driver\WriteConcern::MAJORITY, 1000);
$result = $manager->executeBulkWrite('test.runoob', $bulk, $writeConcern);
改
$manager = new MongoDB\Driver\Manager("mongodb://localhost:27017");
$bulk = new MongoDB\Driver\BulkWrite;
//如果加了$set 是修改指定元素,如果不加,就是整个替换
//multi=false时:只更新找到的第一条记录 true 时,修改全部(修改全部时,必须加$set,否则报错)
//upsert=false时:不符合条件,就不插入 true 时,没有修改符合的就增加一条数据
$bulk->update(
['cid' => '3333'],
// ['title' => '都改了吧啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊','id'=>2,'cid'=>'3333'],
['$set' => ['title' => '都改了吧啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊', 'id' => 2, 'cid' => '3333']],
['multi' => true, 'upsert' => false]
);
$writeConcern = new MongoDB\Driver\WriteConcern(MongoDB\Driver\WriteConcern::MAJORITY, 1000);
$result = $manager->executeBulkWrite('test.runoob', $bulk, $writeConcern);
查
$manager = new MongoDB\Driver\Manager("mongodb://localhost:27017");
//查询条件
$filter = array();
$filter = ['$where' => 'this.id>0'];
//$in 是 in的作用
$filter = ['id' => ['$in' => [1, 2]]];
//用_id查询
$filter['_id'] = new MongoDB\BSON\ObjectId('61cd4888a16d0000cd002d14');
//附加信息
$options = [
'projection' => ['_id' => 0],//这个样子显示全部内容,也可以是'_id'=>0
'sort' => ['id' => -1],//根据user_id字段排序,1是升序,-1是降序
// 'limit'=>'1'取几行数据
// 'skip'=>'1'跳过几行数据不包含本条
];
$query = new MongoDB\Driver\Query($filter, $options);
$cursor = $manager->executeQuery('test.runoob', $query);
foreach ($cursor as $document) {
//获取_id
print_r($document->_id->__toString());
print_r($document);
}
//如果需要查询条数,有别的方法,不过也是先查询所有的,再进行操作,
$data = $cursor->toArray();
var_dump($data);