P K
P K

Reputation: 10210

Multiple document update issue in mongodb

Does MongoDB support multiple document update if selector (first argument) is selecting more than 1 document inside a collection.

In the below example first one works fine as it selects only a particular document and modifies zip value.

While in second case collection $addresses has multiple documents which has 'home' => 'canada', it doesn't update anything.

Can someone please help me ?

$addresses->update(array('_id' => new MongoId('4f69de380c211d6c21000001')),
               array('$set' => array('zip' => 20)));

$addresses->update(array('home' => 'canada')),
               array('$set' => array('zip' => 20)));

Edit:

Equivalent javascript command

db.addresses.update({home: "canada"}, {$set: {zip: 20}})

Updates zip value of first encountered match, is this the expected behavior.

console command is updating at least one document, PHP is not doing anything if selector matches more than 1 document.

Upvotes: 1

Views: 509

Answers (1)

spf13
spf13

Reputation: 561

As long as the second statement matches anything it should always update a single document.

If you want it to apply to multiple documents you should pass in the multiple flag as documented here.

http://www.php.net/manual/en/mongocollection.update.php

In your case the query should read:

$addresses->update(array('home' => 'canada'),
           array('$set' => array('zip' => 20)),
           array('multiple' => true)
);

Upvotes: 3

Related Questions