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  ) 
                         ));
    
    评论

报告相同问题?

悬赏问题

  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料