大家好,我是考100分的小小码 ,祝大家学习进步,加薪顺利呀。今天说一说PHP7操作MongoDB[通俗易懂],希望您对编程的造诣更进一步.
PHP7里面使用如下库,操作比较复杂
PHP7连接MongoDB语法如下:
//参数规则: mongodb://账号:密码@IP:端口/数据库
$manager = new MongoDBDriverManager("mongodb://php:123456@localhost:27017/php");
代码100分
插入数据
代码100分//1.连接MongoDB
$manager = new MongoDBDriverManager("mongodb://php:123456@localhost:27017/php");
//2.创建一个BulkWrite对象
$bulk = new MongoDBDriverBulkWrite();
$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 MongoDBDriverManager("mongodb://php:123456@localhost:27017/php");
//2.创建一个Query对象
$filter = ["age" => ["$gt" => 5]];
$options = [
"sort" => ["age" => -1]
];
$query = new MongoDBDriverQuery($filter, $options);
$cursor = $manager->executeQuery("php.stu", $query);
foreach ($cursor as $document) {
var_dump($document);
}
更新数据
代码100分//1.规则:mongodb://账号:密码@IP:端口/数据库
$manager = new MongoDBDriverManager("mongodb://php:123456@localhost:27017/php");
//2.创建一个BulkWrite对象
$bulk = new MongoDBDriverBulkWrite();
$bulk->update(
["age" => 12],
["$set" => ["name" => "kitty", "age" => 122]],
["multi" => false, "upsert" => false]
);
$writeConcern = new MongoDBDriverWriteConcern(MongoDBDriverWriteConcern::MAJORITY, 1000);
$result = $manager->executeBulkWrite("php.stu", $bulk, $writeConcern);
删除数据
//1.规则:mongodb://账号:密码@IP:端口/数据库
$manager = new MongoDBDriverManager("mongodb://php:123456@localhost:27017/php");
//2.创建一个BulkWrite对象
$bulk = new MongoDBDriverBulkWrite();
//limit为1时,删除第一条匹配的数据
//limit为0时,删除所有匹配数据
$bulk->delete(["age" => 122], ["limit" => 1]);
$writeConcern = new MongoDBDriverWriteConcern(MongoDBDriverWriteConcern::MAJORITY, 1000);
$result = $manager->executeBulkWrite("php.stu", $bulk, $writeConcern);
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
转载请注明出处: https://daima100.com/7002.html