sankar muniyappa
sankar muniyappa

Reputation: 356

How to use updateMany query in PHP with MongoDB

In MongoDB 3.2 they have give update multiple documents with one query like below

try {
   db.inspectors.updateMany(
      { "inspector" : "J. Clouseau", "Sector" : 4 },
      { $set: { "Patrolling" : false } },
      { upsert: true }
   );
}
catch (e) {
   print(e);
}

I've checked php website for MongoDB for this query not having function for this.

Upvotes: 3

Views: 3525

Answers (2)

Manu Eidenberger
Manu Eidenberger

Reputation: 2096

Pay attention since there are two versions of mongodb drivers for php. Mongodb 3.2 requires the mongodb.so driver version, which is different from mongo.so (and now deprecated).

Also, as mentionned in the mongodb.so documentation on php.net :

Application developers should consider using this extension in conjunction with the MongoDB PHP library [...]

This official library provides the usual mongodb CRUD functions, on top of the new mongodb.so driver, and the librarie's documentation also says you can make use updateMany() as you would do it in javascript:

$updateResult = $collection->updateMany(
    ["inspector" => "J. Clouseau", "Sector" => 4 ],
    ['$set' => ['Patrolling' => false]]
);

printf("Matched %d document(s)\n", $updateResult->getMatchedCount());
printf("Modified %d document(s)\n", $updateResult->getModifiedCount());

Upvotes: 4

CEDA
CEDA

Reputation: 55

You can use MongoDB_DataObject as example below:

$model = new MongoDB_DataObject('inspectors');

$model->Patrolling = false;

$model->whereAdd("inspector = 'J. Clouseau' and Sector = 4");

$model->update();

Upvotes: -1

Related Questions