mongodb嵌入式更新对象

时间:2013-03-04 17:49:18

标签: php mongodb

我有这个结构:

{
 "_id": NumberInt(101),
 "link_id": {
 "125": {
   "thumb_position": NumberInt(1),
   "last_scan": NumberInt(1234563645),
   "row_numb": NumberInt(301),
   "clicks": NumberInt(120)
   },
 "126": {
   "thumb_position": NumberInt(2),
   "last_scan": NumberInt(-2147483648),
   "row_numb": NumberInt(1301),
   "clicks": NumberInt(199)
     },
    {
    ...
    }
}
}   

我想用新的linkid更新文档并获取:

{
"_id": NumberInt(101),
"link_id": {
  "125": {
   "thumb_position": NumberInt(1),
   "last_scan": NumberInt(1234563645),
   "row_numb": NumberInt(301),
   "clicks": NumberInt(120)
},
 "126": {
   "thumb_position": NumberInt(2),
   "last_scan": NumberInt(-2147483648),
   "row_numb": NumberInt(1301),
   "clicks": NumberInt(199)
},
 "127": {
   "thumb_position": NumberInt(1),
   "last_scan": NumberInt(-2147483628),
   "row_numb": NumberInt(1304),
   "clicks": NumberInt(195)
}
}

我在php中尝试过:

$value = array (
'130' => 
array (
  'thumb_position' => 1,
  'last_scan' => 1234563640,
  'row_numb' => 300,
  'clicks' => 120,
));
$update_status = $collection->update( array('_id'=>intval(101)), array('$set' => array('link_id' => $value)) , array("upsert"=>true ,"multiple"=> true , "safe"=> true) );

但这只是用这个130覆盖了link_ids。

嵌入式aproach ...既然这不是数组,而是对象,任何关于如何解决这个问题的想法?很多。

1 个答案:

答案 0 :(得分:1)

请尝试使用以下代码:

$value = array (
    'thumb_position' => 1,
    'last_scan' => 1234563640,
    'row_numb' => 300,
    'clicks' => 120,
);

$update_status = $collection->update(
    array('_id'=>intval(101)),
    array('$set' => array('link_id.130' => $value)),
    array("upsert"=>true ,"multiple"=> true , "safe"=> true)
);