php操作mongodb:添删改查
1:插入数据
例:向默认的test数据库的wj表中插入数据
$manager = new MongoDB\Driver\Manager("mongodb://localhost:27017");
// 插入数据
$bulk = new MongoDB\Driver\BulkWrite;
$bulk->insert(['id' => 1, 'name'=>'测试', 'url' => 'http://www.百度.com']);
$manager->executeBulkWrite('test.wj', $bulk);
2:查询数据
查询test数据库的wj表中name值不为测试的数据
$manager = new MongoDB\Driver\Manager("mongodb://localhost:27017");
$filter = ['name' => '测试'];
$options = [
'projection' => ['_id' => 0],
'sort' => ['name' => -1],
];
$query = new MongoDB\Driver\Query($filter, $options);
$cursor = $manager->executeQuery('test.wj', $query);
foreach ($cursor as $document) {
print_r($document);
}
3:更新数据
将test数据库中的wj表中id为1的数据中name字段变为测试1234,
$bulk = new MongoDB\Driver\BulkWrite;
$bulk->update(
['id' => 1],
['$set' => ['name' => '测试1234']],
['multi' => false, 'upsert' => false] #multi表示只更新一条数据,upsert表示如果不存在update的记录,不进行插入操作
);
$manager = new MongoDB\Driver\Manager("mongodb://localhost:27017");
$writeConcern = new MongoDB\Driver\WriteConcern(MongoDB\Driver\WriteConcern::MAJORITY, 1000);
$result = $manager->executeBulkWrite('test.wj', $bulk, $writeConcern);
广州VI设计公司https://www.houdianzi.com
4:删除数据
$bulk = new MongoDB\Driver\BulkWrite;
$bulk->delete(['id' => 1], ['limit' => 1]); // limit 为 1 时,删除第一条匹配数据
$bulk->delete(['id' => 2], ['limit' => 0]); // limit 为 0 时,删除所有匹配数据
$manager = new MongoDB\Driver\Manager("mongodb://localhost:27017");
$writeConcern = new MongoDB\Driver\WriteConcern(MongoDB\Driver\WriteConcern::MAJORITY, 1000);
$result = $manager->executeBulkWrite('test.wj', $bulk, $writeConcern);