开发者

PHP MongoDB update multiple fields with one query

I've tried running this query:

$collection->update(
    array('_id' => 'mongoIDhere'),
    array(
        '$set' => array("parent" => 'data'),
        array("parents" => 'data')
    ),
    array("upsert" => true)
);

But开发者_运维百科 it will only update the second "set" parameter (which is array("parents" => 'data') ). When done in two separate queries these work fine, but together it doesn't - what gives?!


$collection->update(
    array('_id' => 'mongoIDhere'),
    array(
        '$set' => array("parent" => 'data'),
    ),
    array("upsert" => true)
);

Remember MongoDB only accepts array in format of key->value pair i.e. array("parents" => 'data') should be $something => array("parents" => 'data') OR make changed in your php.ini file so that it will be allow null values as key.


Try with multiple option

$collection->update(
    array('_id' => 'mongoIDhere'),
    array('$set' => array("parent" => 'data')),
    array("upsert" => true, "multiple" => true)
);

"multiple" option

All documents matching $criteria will be updated. MongoCollection::update() has exactly the opposite behavior of MongoCollection::remove(): it updates one document by default, not all matching documents. It is recommended that you always specify whether you want to update multiple documents or a single document, as the database may change its default behavior at some point in the future.

Mongocollection in PHP Doc's


Try something like this.

$collection->update(
            array('_id' => 'mongoIDhere'),
            array(
                '$set' => 
                          array(
                                 array("parent" => 'data'),
                                 array("parents" => 'data')
                               )
            ),
            array("upsert" => true) 
         );

Hope this will work..


Assuming that you are using https://github.com/mongodb/mongo-php-library you should try this:

$collection->update(
  ['_id' => 'mongoIDhere],
  ['$set' => ['parent' => 'data', 'parent2' => 'data2']],
  ['upsert' => true]
);

I hope that you found a way to fix your issue since you asked the question. However I faced same issue today and couldn't find any answer with search engines so I though that this might help other fellas.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜