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
如您从本文得到了有价值的信息或帮助,请考虑扫描文末二维码捐赠和鼓励。
如本文对您有用,捐赠和留言 将是对我最好的支持~(捐赠可转为站内积分)
如愿意,请向朋友推荐本站,谢谢。
尊重他人劳动成果。转载请务必附上原文链接,我将感激不尽。