Upsert-PHP Mongodb-无法插入新记录
作者:互联网
我正在运行以下代码.如果记录已经存在,则将其替换为$updated_fields_array中的新字段.但是,如果记录不存在,我将不知道如何添加具有新字段($new_fields_array)的新记录.我应该使用哪个操作符?有人可以帮我吗?
$current_time = time();
$current_mongo_date = new MongoDate($current_time);
$collection = $this->mongo->selectCollection(MONGO_NOTIFY_DB, 'AccountSettings');
$criteria_array=array("email" => $email, "name" => $name);
$updated_fields_array = array (
'last_sent' => $current_time,
'updated' => $current_mongo_date
);
$new_fields_array = array (
'created' => $current_mongo_date,
'updated' => $current_mongo_date,
'email' => $email,
'name' => $name,
'last_sent' => $current_time,
'deleted' => FALSE
);
try {
$collection->update(
$criteria_array,
array('$set' => $updated_fields_array),
array("upsert" => true)
);
} catch (MongoCursorException $mce) {
log_message('error', 'QUERY UPDATE FAILED :: AccountSettings :: ' . print_r($updated_fields_array, true) . ' :: ' . $mce->getMessage());
}
return;
解决方法:
叶夫根尼的答案还可以,但您缺少一个问题
您在update_fields_array和new_fields_array中有重复的键,这会引发MongoDB WriteException,因为Mongo首先会创建新对象,然后才对其进行更新.
所以改变
$updated_fields_array = array (
'last_sent' => $current_time,
'updated' => $current_mongo_date
);
$new_fields_array = array (
'created' => $current_mongo_date,
'updated' => $current_mongo_date,
'email' => $email,
'name' => $name,
'last_sent' => $current_time,
'deleted' => FALSE
);
至
$updated_fields_array = array (
'last_sent' => $current_time,
'updated' => $current_mongo_date
);
$new_fields_array = array (
'created' => $current_mongo_date,
'email' => $email,
'name' => $name,
'deleted' => FALSE
);
并更改查询(如Evgeny所写或Documentation)
$collection->update(
$criteria_array,
array('$set' => $updated_fields_array, '$setOnInsert'=> $new_fields_array),
array("upsert" => true)
);
标签:upsert,mongodb,php 来源: https://codeday.me/bug/20191118/2031967.html