duanli5662 2014-07-17 12:06
浏览 78
已采纳

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());

Here is what it inserts

{
   "_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") 
    } 
  } 
}

however when I try to post another status it should add it to stats and not override the subarray has it keeps doing.

I tried

$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)

and it did not work it added this to the collection

{
   "_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条回答 默认 最新

  • doubiao7410 2014-07-17 12:41
    关注

    I'm not a PHP developer but I guess the query should be constructed as follows:

    $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)
    );
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改