MongoDB upsert - 子数组不会添加子数组

时间:2014-07-17 12:06:38

标签: php mongodb upsert

static::db()->resetError();
$wherehash = array("hashtag" => $hashtag[$j]);
$hash->update($wherehash,array("hashtag" => $hashtag[$j],"lastused"=>new MongoDate(), "stats" => array(array("statusId"=>new MongoId($status['_id']),"timestamp"=>new MongoDate()))),array('safe'=>true,'upsert' => true));

var_dump(static::db()->lastError());

这是它插入的内容

{
   "_id": ObjectId("53c7b94166e6eb75b52c599b"),
   "hashtag": "#hashtag",
   "lastused": ISODate("2014-07-17T12:03:58.980Z"),
   "stats": {
     "0": {
       "statusId": ObjectId("53c7bbaee7fda80e0d8b4567"),
       "timestamp": ISODate("2014-07-17T12:03:58.980Z") 
    } 
  } 
}

然而,当我尝试发布另一个状态时,它应该将其添加到统计数据中,而不是覆盖它继续执行的子数组。

我试过

$hash->update($wherehash,array("hashtag" => $hashtag[$j],"lastused"=>new MongoDate(), "stats" => array('$push'=>array("statusId"=>new MongoId($status['_id']),"timestamp"=>new MongoDate()))),array('safe'=>true,'upsert' => true)

它没有用,它将它添加到集合

{
   "_id": ObjectId("53c7b94166e6eb75b52c599b"),
   "hashtag": "#hashtag",
   "lastused": ISODate("2014-07-17T12:31:20.738Z"),
   "stats": {
     "$push": {
       "statusId": ObjectId("53c7c218e7fda8641e8b4567"),
       "timestamp": ISODate("2014-07-17T12:31:20.738Z") 
    } 
  } 
}

1 个答案:

答案 0 :(得分:0)

我不是PHP开发人员,但我想这个查询应该按如下方式构建:

$hash->update($wherehash,
    array(
        "$set" => array(
            "hashtag" => $hashtag[$j],
            "lastused" => new MongoDate()
        ),
        "$push" => array(
            "stats" => array(
                "statusId" => new MongoId($status['_id']),
                "timestamp" => new MongoDate()
            )
        )
    ),
    array('safe' => true, 'upsert' => true)
);