将值添加到MongoDB文档中的数组

时间:2013-07-28 17:57:18

标签: php mongodb

假设我们有这份文件:

Array
(
    [created_at] => 1373767280
    [email] => admin@mysite.com
    [emailQueries] => Array
        (
            [21] => 1
        )
    [last_visit] => 1375033640
)

要更新emailQueries字段,我会这样做:

$updateEmailQueries['emailQueries']['22'] = 1;
$collection->update( array('email' => $user['email']), array( '$set' => $updateEmailQueries ) );

它更新它,但它总是替换数组中的现有项目(即[21] => 1这里将变为[22] => 1)。 我的目标是为数组添加值,并使其看起来像:

    [emailQueries] => Array
        (
            [21] => 1
            [22] => 1

        )

我尝试添加第二个'$set',但似乎没有。

更新

我试过了:

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

我得到了

Fatal error: Uncaught exception 'MongoCursorException' with message 'localhost:27017: Cannot apply $push/$pushAll modifier to non-array';

1 个答案:

答案 0 :(得分:1)

您正在寻找$push operator

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