【发布时间】:2012-09-11 11:00:59
【问题描述】:
我有一个 mongodb 集合,格式为
{ "_id" : ObjectId("50072b17b4a6de3b1100000f")
"employment_details" : [
{
"_id" : ObjectId("50072b17b4a6de3b11000015"),
"title" : "Information Technology Compliance & Security",
"rank" : null,
"department" : null,
"current" : true,
"company_id" : ObjectId("5007269fb4a6de941001d19d")
}
]
}
我需要的是,如果“employment_details”数组为空或不存在,我需要创建新值并将其插入到employment_details 中,否则我需要推送像这样的细节,
{ "_id" : ObjectId("50072b17b4a6de3b1100000f")
"employment_details" : [
{
"_id" : ObjectId("50072b17b4a6de3b11000015"),
"title" : "Information Technology Compliance & Security",
"rank" : null,
"department" : null,
"current" : false,
"company_id" : ObjectId("5007269fb4a6de941001d19d")
}
......
{
"_id" : ObjectId("50072b17b4a6de3b11000018"),
"title" : "security engineer",
"rank" : null,
"department" : null,
"current" : false,
"company_id" : ObjectId("5007269fb4a6de941001dasd")
}
{
"_id" : ObjectId("50072b17b4a6de3b11000016"),
"title" : "software Engineer",
"rank" : null,
"department" : null,
"current" : true,
"company_id" : ObjectId("5007269fb4a6de94100189e")
}
]
}
但棘手的部分是,由于我正在推送特定员工的就业详细信息,因此必须设置“employment_details”中的“current”字段 true 仅适用于新插入的联系人,旧 employment_details 中的所有其他“current”字段必须设置为 false,就像我提到的在上面的例子中。
实际上,当插入一个新的 employement_detail 时,它的 current 字段必须设置为 true,而所有其他 current > 以前的就业详情中的字段必须设置为 false。
我知道推送值的一般语法,但是如何更新旧值和推送新值?
希望我的问题很清楚。
更新代码(我试过的):
$my_collection->update(
array("_id"=>$id),
array('$push' =>
array(
"employment_details" => array("title" => $title, "rank" => $rank, "department" => $dept, "current" => "true", "company_id" => $c_id)
))
);
但我不知道如何更新以前的值。
【问题讨论】:
-
是否有一小段代码您实际尝试过?
-
$my_collection->update(array("_id"=>$id), array('$push' =>array("employment_details" => array("title" => $title, "rank" => $rank, "current" => "true", "company_id" => $c_id))));
-
但我真的不知道如何更新以前的值。 @dbf
-
请将所有未来的代码请求编辑到您的原始帖子中,已经为您编辑了这个。
-
好的。如果您知道,请发布答案。
标签: php mongodb push mongodb-php