PHP7 MongoDB 使用方法

来源:赵克立博客 分类: NOSQL 标签:mongoDB发布时间:2019-05-28 10:19:57最后更新:2019-05-28 16:40:26浏览:1358
版权声明:
本文为博主原创文章,转载请声明原文链接...谢谢。o_0。
更新时间:
2019-05-28 16:40:26
温馨提示:
学无止境,技术类文章有它的时效性,请留意文章更新时间,如发现内容有误请留言指出,防止别人"踩坑",我会及时更新文章

MongoDb原生操作

Mongodb连接

PHP7 连接 MongoDB 语法如下:

$manager = new MongoDB\Driver\Manager("mongodb://localhost:27017");

插入数据

将 name 为"自学教程" 的数据插入到 test 数据库的 runoob 集合中。

$bulk = new MongoDB\Driver\BulkWrite;
$document = ['_id' => new MongoDB\BSON\ObjectID, 'name' => '菜鸟教程'];
 
$_id= $bulk->insert($document);
 
var_dump($_id);
 
$manager = new MongoDB\Driver\Manager("mongodb://localhost:27017");  
$writeConcern = new MongoDB\Driver\WriteConcern(MongoDB\Driver\WriteConcern::MAJORITY, 1000);
$result = $manager->executeBulkWrite('test.runoob', $bulk, $writeConcern);

读取数据

$manager = new MongoDB\Driver\Manager("mongodb://localhost:27017");  
 
// 插入数据
$bulk = new MongoDB\Driver\BulkWrite;
$bulk->insert(['x' => 1, 'name'=>'baidu', 'url' => 'http://www.baidu.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.sites', $bulk);
 
$filter = ['x' => ['$gt' => 1]];
$options = [
    'projection' => ['_id' => 0],
    'sort' => ['x' => -1],
];
 
// 查询数据
$query = new MongoDB\Driver\Query($filter, $options);
$cursor = $manager->executeQuery('test.sites', $query);
 
foreach ($cursor as $document) {
    print_r($document);
}

更新数据

$bulk = new MongoDB\Driver\BulkWrite;
$bulk->update(
    ['x' => 2],
    ['$set' => ['name' => '菜鸟工具', 'url' => 'tool.runoob.com']],
    ['multi' => false, 'upsert' => false]
);
 
$manager = new MongoDB\Driver\Manager("mongodb://localhost:27017");  
$writeConcern = new MongoDB\Driver\WriteConcern(MongoDB\Driver\WriteConcern::MAJORITY, 1000);
$result = $manager->executeBulkWrite('test.sites', $bulk, $writeConcern);

删除数据

$bulk = new MongoDB\Driver\BulkWrite;
$bulk->delete(['x' => 1], ['limit' => 1]);   // limit 为 1 时,删除第一条匹配数据
$bulk->delete(['x' => 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.sites', $bulk, $writeConcern);

MongoDB官方操作库

看完上面的CURD操作是不是感觉有点懵逼,操作方式跟想像中的完全不一样,可能官方也想到啦这一块,于是又封装啦一个操作库让大家使用。文档地址如下

https://docs.mongodb.com/php-library/current/tutorial/crud/

安装

composer require mongodb/mongodb

添加数据

插入单条数据

在数据库test中的users集合中插入数据,如果数据库或集合不存在则会自动创建

$collection      = (new MongoDB\Client)->test->users;
$insertOneResult = $collection->insertOne([
    'username' => 'admin',
    'email'    => 'admin@example.com',
    'name'     => 'Admin User',
]);
printf("Inserted %d document(s)\n", $insertOneResult->getInsertedCount());
var_dump($insertOneResult->getInsertedId());

输出结果

1905281559025619827923.png

数据库中数据

1905281559025567787873.png

可以看出返回$oid为数据库自动分配的唯一标识,如果我们插入的时候传入id值的话,mongodb会判断这个id是否存在,如果存在就会报错,如果不存在则直接返回传入的id值

$collection      = (new MongoDB\Client)->test->users;
$insertOneResult = $collection->insertOne(['_id' => 1, 'name' => 'Alice']);
printf("Inserted %d document(s)\n", $insertOneResult->getInsertedCount());
var_dump($insertOneResult->getInsertedId());

执行结果

1905281559025985889303.png

插入多条数据

$collection = (new MongoDB\Client)->test->users;
$insertManyResult = $collection->insertMany([
    [
        'username' => 'admin',
        'email' => 'admin@example.com',
        'name' => 'Admin User',
    ],
    [
        'username' => 'test',
        'email' => 'test@example.com',
        'name' => 'Test User',
    ],]);
printf("Inserted %d document(s)\n", $insertManyResult->getInsertedCount());
var_dump($insertManyResult->getInsertedIds());

1905281559026233129220.png

查询数据

如果要使用id查询,则需要使用下面的ObjectId类来封装下传进去

使用自增id查询

$collection = (new MongoDB\Client)->test->users;
$id         = new \MongoDB\BSON\ObjectId('5cecd708ab4e4536fc0076e2');
$document   = $collection->findOne(['_id' => $id]);
var_dump($document);

其它条件查询

使用其它条件数据则直接传进去就可以 

$collection = (new MongoDB\Client)->test->users;
$document   = $collection->findOne(['username' => 'admin']);
var_dump($document);

1905281559027257136568.png

使用limit,sort,skip查询

默认情况下是返回所有的字段数据,也可以指定字段返回,limit是返回的行数,sort是使用name字段-1为降序,1为升序,skip为跳过前多少条数据如下

$collection = (new MongoDB\Client)->test->users;
$cursor     = $collection->find(
    [
        'username' => 'admin',
    ],
    [
        'projection' => [
            'email' => 1,
        ],
        'limit'      => 4,
        'sort'       => ['name' => -1],
        'skip'       =>1,
    ]);
foreach ($cursor as $restaurant) {
    var_dump($restaurant);
}

正则条件查询

$collection = (new MongoDB\Client)->test->users;
$cursor     = $collection->find(
    [
        'username' => new MongoDB\BSON\Regex('^ad', 'i'),
    ],
    [
        'projection' => [
            'email' => 1,
        ],
        'limit'      => 1,
        'sort'       => ['pop' => -1],
    ]);
foreach ($cursor as $restaurant) {
    var_dump($restaurant);
}

另外一种正则式的写法

$collection = (new MongoDB\Client)->test->users;
$cursor     = $collection->find(
    [
        'username' => ['$regex' => '^ad', '$options' => 'i'],
    ],
    [
        'projection' => [
            'email' => 1,
        ],
        'limit'      => 1,
        'sort'       => ['pop' => -1],
    ]);
foreach ($cursor as $restaurant) {
    var_dump($restaurant);
}

查询多个数据

$collection = (new MongoDB\Client)->test->users;
$cursor     = $collection->find(['username' => 'admin']);
foreach ($cursor as $document) {
    echo $document['_id'], "\n";
}

1905281559027339129636.png

更新数据

更新单条数据

$collection   = (new MongoDB\Client)->test->users;
$updateResult = $collection->updateOne(
    ['username' => 'admin'],
    ['$set' => ['name' => 'new nickname']]
);
printf("Matched %d document(s)\n", $updateResult->getMatchedCount());
printf("Modified %d document(s)\n", $updateResult->getModifiedCount());

1905281559029206114764.png

更新多条数据

$collection   = (new MongoDB\Client)->test->users;
$updateResult = $collection->updateMany(
    ['username' => 'admin'],
    ['$set' => ['name' => 'new nickname']]
);
printf("Matched %d document(s)\n", $updateResult->getMatchedCount());
printf("Modified %d document(s)\n", $updateResult->getModifiedCount());

1905281559029272301679.png

替换文档

替换文档其它跟更新数据类似,但是这个操作不会修改id,如下

$collection   = (new MongoDB\Client)->test->users;
$updateResult = $collection->replaceOne(
    ['username' => 'admin'],
    ['username' => 'admin2', 'name' => 'new nickname']
);
printf("Matched %d document(s)\n", $updateResult->getMatchedCount());
printf("Modified %d document(s)\n", $updateResult->getModifiedCount());

Upsert操作

这个名字应该是个缩写,更新或替换操作时如果有匹配的数据则直接操作,如果没有匹配的数据则插入一条新数据,意思是如果更新或替换操作的第三个参数如果传 'upsert'=>True 的话就可以开启这个功能

$collection   = (new MongoDB\Client)->test->users;
$updateResult = $collection->updateOne(
    ['username' => 'admin3'],
    ['$set' => ['username' => 'admin2', 'name' => 'new nickname']],
    ['upsert' => true]
);
printf("Matched %d document(s)\n", $updateResult->getMatchedCount());
printf("Modified %d document(s)\n", $updateResult->getModifiedCount());
printf("Upserted %d document(s)\n", $updateResult->getUpsertedCount());
$upsertedDocument = $collection->findOne([
    '_id' => $updateResult->getUpsertedId(),
]);
var_dump($upsertedDocument);

如果有匹配的情况下最后输出为NULl

1905281559030215132171.png

没有匹配的情况下最后输出插入的数据

1905281559030085203984.png

删除数据

$collection   = (new MongoDB\Client)->test->users;
$deleteResult = $collection->deleteOne(['username' => 'admin3']);
printf("Deleted %d document(s)\n", $deleteResult->getDeletedCount());
$deleteResult = $collection->deleteMany(['username' => 'admin2']);
printf("Deleted %d document(s)\n", $deleteResult->getDeletedCount());

1905281559030350141184.png


微信号:kelicom QQ群:215861553 紧急求助须知
Win32/PHP/JS/Android/Python