这是我的MongoDB Collection文档。
{
"_id":"5b6361e2b17cf5286c7c3e84",
"user":"ishwar",
"content":"this is the first post",
"likes":[
{
"user":"john"
}
],
"comments":[
{
"user":"bill",
"content":"congrats on first post"
},
{
"user":"mark",
"content":"great job"
}
]
}
我正在尝试从评论的第一个对象更新内容。即我想按帐单将注释更改为“嗯”。
我正在将MongoDB Driver与php7.2配合使用。我已经编写了自己的函数。
我的代码
$mongo = new MongoDB\Driver\Manager("mongodb://localhost:27017");
function mongoId($id = "") {return $id == "" ? new MongoDB\BSON\ObjectId : new MongoDB\BSON\ObjectId($id);}
function mongoWrite($method, $records, $dbCollection, $filter = [], $options = ['upsert' => false]) {
$bulk = new MongoDB\Driver\BulkWrite;
if ($method == "insert") {
foreach ($records as $record) {
$bulk->insert($record);
}
} elseif ($method == "update") {
foreach ($records as $record) {
$bulk->update($filter, ['$set'=> $record], $options);
}
}
return $GLOBALS['mongo']->executeBulkWrite($dbCollection, $bulk);
}
$array = [];
$array['comments'][0]['content'] = "Hmmm";
var_dump(mongoWrite("update", [$array], "allPosts.temp", ["user" => 'ishwar']));
结果是
{
"_id":"5b6361e2b17cf5286c7c3e84",
"user":"ishwar",
"content":"this is the first post",
"likes":[
{
"user":"john"
}
],
"comments":[
{
"user":"bill",
"content":"congrats on first post"
},
{
"user":"mark",
"content":"great job"
}
],
"comments":[
{
"content":"Hmmm"
}
]
}
将插入新字段,而不是更新旧字段。我正在从MySQL转移到MongoDB。我尝试在BulkWrite选项中设置['upsert' => false]
,但没有任何反应。
感谢您的宝贵时间。