请知悉:本文最近一次更新为 4年 前,文中内容可能已经过时。

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


如您从本文得到了有价值的信息或帮助,请考虑扫描文末二维码捐赠和鼓励。

尊重他人劳动成果。转载请务必附上原文链接,我将感激不尽。


与《PHP mongodb驱动增删查改示例》相关的博文:


留言

avatar
😀
😀😁😂😅😭🤭😋😘🤔😰😱🤪💪👍👎🤝🌹👌