我发现的所有内容都使用MongoClient-不适用于当前的php驱动程序。 how to update and insert records in php using mongodb(以及许多其他类似的东西都使用MongoClient)
文档...呃...我们应该说还有很多不足之处。 http://php.net/manual/en/book.mongodb.php
我的尝试归结为这个...
$filter = [];
if (isset($_REQUEST['needleKey'])) {
$needleKey = $_REQUEST['needleKey'];
$needle= $_REQUEST['needle'];
$filter = [$needleKey => $needle];
}
$newData = $_REQUEST['newData'];
//Manager Class
$connection = new MongoDB\Driver\Manager("mongodb://${user}:${pwd}@XXX.XXX.XXX.XXX:27017");
// Query Class
$query = new MongoDB\Driver\Query($filter);
$connection->upsert($query, $newData);
在过去3天里,我尝试了许多其他事情,但没有运气。有没有人有使用php更新mongodb的基本示例?
根据文档,此代码似乎可以工作-但它还会返回服务器错误:
$filter = [];
if (isset($_REQUEST['needleKey'])) {
$needleKey = $_REQUEST['needleKey'];
$needle = $_REQUEST['needle'];
$filter = [$needleKey => $needle];
}
$newData = $_REQUEST['newData'];
$bulk = new MongoDB\Driver\BulkWrite;
$bulk->update(
$filter,
$newData,
['multi' => true, 'upsert' => true]
);
//Manager Class
$connection = new MongoDB\Driver\Manager("mongodb://${user}:${pwd}@xxx.xxx.xxx.xxx:27017");
$result = $connection->executeBulkWrite('db.defaultConfig', $bulk);
echo json_encode($result);
我进一步尝试了php页面上记录的解决方案:http://php.net/manual/en/mongodb-driver-bulkwrite.insert.php
$bulk = new MongoDB\Driver\BulkWrite;
$document1 = ['title' => 'one'];
$document2 = ['_id' => 'custom ID', 'title' => 'two'];
$document3 = ['_id' => new MongoDB\BSON\ObjectId, 'title' => 'three'];
$_id1 = $bulk->insert($document1);
$_id2 = $bulk->insert($document2);
$_id3 = $bulk->insert($document3);
var_dump($_id1, $_id2, $_id3);
$manager = new MongoDB\Driver\Manager('mongodb://${user}:${pwd}@localhost:27017');
$result = $manager->executeBulkWrite('db.collection', $bulk);
这还将返回服务器错误。如果删除最后一行,它将返回var dump的结果..但是,只要我包括了最后一行。 (db和collection指向我的收藏集)我收到500个服务器错误。