我有一个 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 ”字段必须仅针对新插入的联系人设置为真,旧的employment_details中的所有其他“ current ”字段必须设置false,就像我在上面的例子中提到的那样。
实际上,当插入新的employment_detail时,它的当前字段必须设置为true,并且之前的employment_details 中的所有其他当前字段必须设置为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)
))
);
但我不知道如何更新以前的值。