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

报告相同问题?

悬赏问题

  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?