php7操作mongodb
2020-10-28 本文已影响0人
江江简书
mongodb是一个介于关系型数据库和非关系型数据库间的数据库,而且能够实现排序等相关的操作,是对redis的一个升级,同时mongodb中的数据库和mysql的类似,数据库的集合和redis相似,开启我们对mongodb的认识吧。
1.插入数据
$manager = new MongoDB\Driver\Manager('mongodb://localhost:27017');
$bulk = new MongoDB\Driver\BulkWrite;
$bulk->insert(['name' => 'phptest', 'age' => 27]);
$bulk->insert(['name' => 'phptest1', 'age' => 28]);
//
$writeConcern = new MongoDB\Driver\WriteConcern(MongoDB\Driver\WriteConcern::MAJORITY, 1000);//可选,修改确认
$res = $manager->executeBulkWrite('flstest.mongo', $bulk, $writeConcern)->getInsertedCount(); //获取插入成功返回的条数
echo '<pre>';
var_dump($res);
2.删除数据
$manager = new MongoDB\Driver\Manager('mongodb://localhost:27017');
$bulk = new MongoDB\Driver\BulkWrite;
$bulk->delete(['name' => 'phptest']);
$writeConcern = new MongoDB\Driver\WriteConcern(MongoDB\Driver\WriteConcern::MAJORITY, 1000);//可选,修改确认
$res = $manager->executeBulkWrite('flstest.mongo', $bulk, $writeConcern)->getDeletedCount(); //获取成功删除的条数
echo '<pre>';
var_dump($res);
3.修改数据
$manager = new MongoDB\Driver\Manager('mongodb://localhost:27017');
$bulk = new MongoDB\Driver\BulkWrite;
$bulk->update(
['name' => 'phptest'],
['$set' => ['age' => 34, 'promise' => '2222']]
);
$writeConcern = new MongoDB\Driver\WriteConcern(MongoDB\Driver\WriteConcern::MAJORITY, 1000);//可选,修改确认
$res = $manager->executeBulkWrite('flstest.mongo, $bulk, $writeConcern)->getModifiedCount(); //获取更新的条数
echo '<pre>';
print_r($res);
4.查询数据
//数据查询操作
$manager = new MongoDB\Driver\Manager('mongodb://localhost:27017');
$query = new MongoDB\Driver\Query(['age' => 26], ['sort' => ['age' => 1]]);
$cursor = $manager->executeQuery('fls_db.test', $query)->toArray();
foreach($cursor as $doc) {
echo '<pre>';
var_dump($doc->name,$doc->age);
}
//这里还不知道怎样获取id,下次找到回头添加进去