douba3378 2013-07-28 22:56
浏览 66

MongoDB更新查询(更新文档中的数组字段)

Here's what the document looks like now.

Array
(
    [email] => admin@mysite.com
    [emailQueries] => Array
        (
            [0] => Array
                (
                    [21] => 0
                )

            [1] => Array
                (
                    [21] => 0
                )

        )

    [last_visit] => 1375050871
)

Here's the code I am using to populate the emailQueries

$arrayValueToAdd = array( (string) $email_id => '0' );

$collection->update( array('email' => $user['email']), 
                     array( '$push' => 
                          array( 'emailQueries' => $arrayValueToAdd ) 
                      )
                  );

However, I'd like to simply have the emailQueries array look like:

[emailQueries] => Array
    (
        [21] => 0
        [22] => 0
    )

Probably a simple thing I'm overlooking...

  • 写回答

1条回答 默认 最新

  • douzhongjian0752 2013-09-04 08:45
    关注

    You are using the array operator push with a data structure that is not considered by MongoDb as an array (array must have 0-based ascending numeric indexes). You must treat it as an object. So you have 2 choices.

    If in [21] => 0, the value 0 is useless (and I don't expect so), you can use a true array:

    "emailQueries" : [21,22]
    

    and you can use the push operator in the PHP code like this

    $collection->update( array('email' => $user['email']), 
                         array( '$push' => 
                             array( 'emailQueries' => (string) $email_id ) 
                         ));
    

    On the other hand, if you must keep the value 0, and for instance, increment it, you have to considered your EmailQuery as an object :

    "emailQueries" : {
        "21" : 0,
        "22" : 0
    }
    

    So you can use a simple update to add field in emailQueries :

    $collection->update( array('email' => $user['email']), 
                         array( '$set' => 
                             array( 'emailQueries.'.$email_id => 0  ) 
                         ));
    

    And the $inc, for incrementation :

    $collection->update( array('email' => $user['email']), 
                         array( '$inc' => 
                             array( 'emailQueries.'.$email_id => 1  ) 
                         ));
    
    评论

报告相同问题?

悬赏问题

  • ¥15 在获取boss直聘的聊天的时候只能获取到前40条聊天数据
  • ¥20 关于URL获取的参数,无法执行二选一查询
  • ¥15 液位控制,当液位超过高限时常开触点59闭合,直到液位低于低限时,断开
  • ¥15 marlin编译错误,如何解决?
  • ¥15 有偿四位数,节约算法和扫描算法
  • ¥15 VUE项目怎么运行,系统打不开
  • ¥50 pointpillars等目标检测算法怎么融合注意力机制
  • ¥20 Vs code Mac系统 PHP Debug调试环境配置
  • ¥60 大一项目课,微信小程序
  • ¥15 求视频摘要youtube和ovp数据集