Xeoncross
Xeoncross

Reputation: 57184

MongoDB increment multiple document array values in PHP

I want to increment all documents in a collection that contain a given nested array value. My objects each contain an "order" array with key:number values.

{
    _id: ...,
    order : array(
        foo: 34
    )
}

However, I can't figure out the correct MongoDB Query using the PHP MongoDB Native Driver.

    // Update all existing items with an order greater than this number
    $number = 2;

    $result = $collection->update(
        array("order" => array('foo' => array('$gt' => $number))),
        array('$inc' => array('order' => array('foo' => 1))),
        array("safe" => true)
    );

Upvotes: 0

Views: 2792

Answers (1)

Chien-Wei Huang
Chien-Wei Huang

Reputation: 1851

This is the PHP version of your MongoDB query and I add a multiple option additionally.

$collection->update(array('order.foo'=>array('$gt'=>2)), array('$inc' => array('order.foo'=>1)), array('multiple'=>true, 'safe'=>true));

Upvotes: 1

Related Questions