0

我有一个 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)
  ))
);

但我不知道如何更新以前的值。

4

1 回答 1

0

您可以首先使用 update 将所有就业细节.current 设置为 false,然后 $push 该字段为 true 的新记录。

当您愿意更改您的架构时,您可以通过使用单个对象 current_employment_detail 和一个 past_employment_detail 数组来更优雅地更改数据库架构。我不知道你的用例,但我猜你需要当前的细节比过去的细节更频繁。当您将其作为单个字段时,您正在保存对就业详细信息当前字段的额外搜索。

于 2012-09-11T11:28:37.283 回答