一,安装php的MongoDB扩展:
Windows10环境(wamp集成环境):https://blog.csdn.net/qq_33210743/article/details/81533980
Linux(centos7):https://www.cnblogs.com/php-linux/p/6187316.html
测试是否安装成功 : php -m ==> 是否有 mongodb扩展
print_r(get_extension_funcs('mongodb')); // 查看是否有该拓展
print_r(get_declared_classes()); // 该扩展中提供了那些函数
这是旧版的php+mongodb参考文档 http://php.net/manual/zh/book.mongo.php
这是新版的php+mongodb参考文档 http://php.net/manual/zh/book.mongodb.php #主要使用这个
二,php+MongoDB的增删改查(新的MongoDB驱动器)
new MongoDB\BSON\ObjectID, 'name' => 'mongodb123'];
$bulk->insert($document);
// 增加方法二,分的
$bulk->insert(['x' => 1, 'name' => '菜鸟教程', 'url' => 'http://www.runoob.com']);
$bulk->insert(['x' => 2, 'name' => 'Google', 'url' => 'http://www.google.com']);
$bulk->insert(['x' => 3, 'name' => 'taobao', 'url' => 'http://www.taobao.com']);
$writeConcern = new MongoDB\Driver\WriteConcern(MongoDB\Driver\WriteConcern::MAJORITY, 1000);
// test.col ==> db.collection
$result = $mongo->executeBulkWrite('test.test1', $bulk, $writeConcern);
/******************* 读取 *************/
$manager = new MongoDB\Driver\Manager("mongodb://localhost:27017");
$bulk = new MongoDB\Driver\BulkWrite;
// 1,增加数据,增加后注释
//$bulk->insert(['x' => 1, 'name' => '菜鸟教程', 'url' => 'http://www.runoob.com']);
//$bulk->insert(['x' => 2, 'name' => 'Google', 'url' => 'http://www.google.com']);
//$bulk->insert(['x' => 3, 'name' => 'taobao', 'url' => 'http://www.taobao.com']);
//$manager->executeBulkWrite('test.test1', $bulk);
// 2,filter实现的是筛选出 某条数据,projection实现的是筛选出某条数据的具体字段
$filter = ['x' => ['$gt' => 1]];
$options = [
'projection' => ['_id' => 0],
'sort' => ['x' => -1],// -1 ==> 升序排列 ; 1 ==> 降序排列
];// 相当于 db.test1.find().sort({'x':-1})
// 3,查询数据
$query = new MongoDB\Driver\Query($filter, $options);
$cursor = $manager->executeQuery('test.test1', $query);
foreach ($cursor as $document) {
print_r($document);
}
/******************* 更新 *************/
$manager = new MongoDB\Driver\Manager("mongodb://localhost:27017");
$bulk = new MongoDB\Driver\BulkWrite;
// upsert : 可选,这个参数的意思是,如果不存在update的记录,是否插入objNew,true为插入,默认是false,不插入。
// multi : 可选,mongodb 默认是false,只更新找到的第一条记录,如果这个参数为true,就把按条件查出来多条记录全部更新。
$bulk->update(
['x' => 2],
['$set' => ['name' => '菜鸟工具1111', 'url' => 'tool.runoob.com']],
['multi' => false, 'upsert' => false]
);
$writeConcern = new MongoDB\Driver\WriteConcern(MongoDB\Driver\WriteConcern::MAJORITY, 1000);// 写操作
$result = $manager->executeBulkWrite('test.test1', $bulk, $writeConcern);
/******************* 删除 *************/
$manager = new MongoDB\Driver\Manager("mongodb://localhost:27017");
$bulk = new MongoDB\Driver\BulkWrite;
$bulk->delete(['x' => 1], ['limit' => 1]); // limit 为 1 时,删除第一条匹配数据
$bulk->delete(['x' => 2], ['limit' => 0]); // limit 为 0 时,删除所有匹配数据
$writeConcern = new MongoDB\Driver\WriteConcern(MongoDB\Driver\WriteConcern::MAJORITY, 1000);
$result = $manager->executeBulkWrite('test.test1', $bulk, $writeConcern);