Mongo DB,PHP在文档中添加或更新字段 [英] Mongo DB, PHP add or update a field in a document
问题描述
我有以下文件:
{
"_id": ObjectId("5241f1d79b7e7aed05000000"),
"description": {
"nl": "Hallo",
"en": "Hello"
},
"name": "Marc"
}
现在,我需要进行更新以更新一个现有字段或在描述中添加新字段.在php中,我对Mongo和以下代码使用了更新功能:
Now I need to update to update one existing field or add new field to the description. In php I use the update function for Mongo and the following code:
$new_data = array(
'$set' => array(
"description" => array(
"de" => "hallo"
)
)
);
它执行的操作将删除所有其他字段,而只需插入"de"字段.我尝试用$ push替换$ set(我认为是这样做的),但是$ setOnInsert也没有任何结果.
What it does it removes all other fields and just insert the "de" field. I tried replacing $set with $push (which I thought was made for this) but no result also $setOnInsert does not do anything.
如何解决此问题,以便我可以添加一个新字段(如果不存在)或进行更新(如果存在).
How can I solve this problem so that I can either add a new field (if it does not exist) or update if it exist.
谢谢
推荐答案
就像进行更新一样
{$set: {"description.de": "hello"}}
我想在您的代码中应该是:
I guess in your code it would be:
$new_data = array(
'$set' => array(
"description.de" => "hallo"
)
);
这篇关于Mongo DB,PHP在文档中添加或更新字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!