码迷,mamicode.com
首页 > 数据库 > 详细

PHP7操作MongoDB

时间:2020-07-29 09:52:05      阅读:74      评论:0      收藏:0      [点我收藏+]

标签:inf   code   数据   log   alt   res   false   update   对象   

PHP7里面使用如下库,操作比较复杂

技术图片

PHP7连接MongoDB语法如下:

//参数规则: mongodb://账号:密码@IP:端口/数据库
$manager = new \MongoDB\Driver\Manager("mongodb://php:123456@localhost:27017/php");

插入数据

//1.连接MongoDB
$manager = new \MongoDB\Driver\Manager("mongodb://php:123456@localhost:27017/php");

//2.创建一个BulkWrite对象
$bulk = new \MongoDB\Driver\BulkWrite();
$bulk->insert([‘name‘ => ‘bashlog‘, ‘age‘ => 26, ‘email‘ => ‘bashlog@foxmail.com‘]);
$bulk->insert([‘name‘ => ‘itbsl‘, ‘age‘ => 12, ‘email‘ => ‘itbsl@foxmail.com‘]);

//3.执行插入
$manager->executeBulkWrite(‘php.stu‘, $bulk);

查看插入情况

技术图片

查询数据

//1.连接MongoDB
$manager = new \MongoDB\Driver\Manager("mongodb://php:123456@localhost:27017/php");

//2.创建一个Query对象
$filter = [‘age‘ => [‘$gt‘ => 5]];
$options = [
    ‘sort‘ => [‘age‘ => -1]
];
$query = new \MongoDB\Driver\Query($filter, $options);
$cursor = $manager->executeQuery(‘php.stu‘, $query);

foreach ($cursor as $document) {
    var_dump($document);
}

更新数据

//1.规则:mongodb://账号:密码@IP:端口/数据库
$manager = new \MongoDB\Driver\Manager("mongodb://php:123456@localhost:27017/php");


//2.创建一个BulkWrite对象
$bulk = new \MongoDB\Driver\BulkWrite();

$bulk->update(
    [‘age‘ => 12],
    [‘$set‘ => [‘name‘ => ‘kitty‘, ‘age‘ => 122]],
    [‘multi‘ => false, ‘upsert‘ => false]
);

$writeConcern = new MongoDB\Driver\WriteConcern(MongoDB\Driver\WriteConcern::MAJORITY, 1000);
$result = $manager->executeBulkWrite(‘php.stu‘, $bulk, $writeConcern);

删除数据

//1.规则:mongodb://账号:密码@IP:端口/数据库
$manager = new \MongoDB\Driver\Manager("mongodb://php:123456@localhost:27017/php");


//2.创建一个BulkWrite对象
$bulk = new \MongoDB\Driver\BulkWrite();
//limit为1时,删除第一条匹配的数据
//limit为0时,删除所有匹配数据
$bulk->delete([‘age‘ => 122], [‘limit‘ => 1]);

$writeConcern = new MongoDB\Driver\WriteConcern(MongoDB\Driver\WriteConcern::MAJORITY, 1000);
$result = $manager->executeBulkWrite(‘php.stu‘, $bulk, $writeConcern);

PHP7操作MongoDB

标签:inf   code   数据   log   alt   res   false   update   对象   

原文地址:https://www.cnblogs.com/itbsl/p/13394636.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!