MongoDB驱动算是比较新的编写方式了,所以整理下增删查改的代码示例:

<?php
#连接
$mongodb = 'mongodb://127.0.0.1:27017/admin?connectTimeoutMS=1000';
$manager = new MongoDB\Driver\Manager($mongodb);

$dbName = "testdb";
$collectionName = "test";
$dbInfo = "{$dbName}.{$collectionName}";#testdb.test

#增或者更新
$data['_id'] = "abc";
$data['other'] = "xxx";
$options = ["upsert"=>true];#存在则更新,否则插入
$bulk = new MongoDB\Driver\BulkWrite($options);
$bulk->update(["_id"=>$data['_id']], $data, $options);
$writeConcern = new MongoDB\Driver\WriteConcern(MongoDB\Driver\WriteConcern::MAJORITY);
$res = $manager->executeBulkWrite($dbInfo, $bulk, $writeConcern);
$m = $res->getModifiedCount();
$u = $res->getUpsertedCount();
$res = $m>$u ? $m:$u;
if($res>0){
#更新或插入成功
}

#删除
$data['_id'] = "abc";
$bulk = new MongoDB\Driver\BulkWrite();
$bulk->delete(["_id"=>$data['_id']]);
$writeConcern = new MongoDB\Driver\WriteConcern(MongoDB\Driver\WriteConcern::MAJORITY);
$res = $manager->executeBulkWrite($dbInfo, $bulk, $writeConcern);

#查询
$query = new MongoDB\Driver\Query(['age' => 24], ['sort' => ['age' => 1]]);
$cursor = $manager->executeQuery($dbInfo, $query);
$data = [];
foreach($cursor as $doc) {
$data[] = $doc;
}

相关参考:https://www.php.cn/php-weizijiaocheng-405061.html

Related Posts: PHP mongodb驱动增删查改示例 :

avatar