MongoWriteBatch
PHP Manual

MongoWriteBatch::add

(PECL mongo >= 1.5.0)

MongoWriteBatch::addAdds an CRUD operation to a batch

Description

public bool MongoWriteBatch::add ( array $item )

The operation to add to the batch.

If $item causes the batch to hit the » maxWriteBatchSize or » maxBsonObjectSize limits, a new batch will be created internally and the batches batched up and sent one at a time upon calling MongoWriteBatch::execute().

Parameters

item

When current batch is Argument expectation
MongoWriteBatch::COMMAND_INSERT The document to add
MongoWriteBatch::COMMAND_UPDATE Raw update operation. Required keys are: array("q" => array("criteria"), "u" => array("new data")) Optionally with the "multi" and "upsert" keys as boolean values
MongoWriteBatch::COMMAND_DELETE Raw delete operation. Required keys are: array("q" => array("criteria"), "limit" => 1)

Return Values

Returns TRUE on success, throws exception on failure.

Errors/Exceptions

Examples

Example #1 MongoWriteBatch::add() example

Batching up multiple insert operations

<?php
$mc 
= new MongoClient("localhost");
$collection $mc->selectCollection("test""test");


$docs = array();
$docs[] = array("my" => "demo");
$docs[] = array("is" => "working");
$docs[] = array("pretty" => "well");

$batch = new MongoInsertBatch($collection);
foreach(
$docs as $document) {
    
$batch->add($document);
}
$batch->execute(array("w" => 1));
?>

Example #2 MongoWriteBatch::add() example

Batching up multiple update operations

<?php
$mc 
= new MongoClient("localhost");
$collection $mc->selectCollection("test""test");


$item1 = array(
    
"q" => array("my" => "demo"),
    
"u" => array('$set' => array("try" => 1)),
    
"multi"  => false/* default value */
    
"upsert" => false/* default value */
);
$item2 = array(
    
"q" => array("is" => "working"),
    
"u" => array('$set' => array("try" => 2)),
    
"multi" => true,
);
$item3 = array(
    
"q" => array("created" => "new-document"),
    
"u" => array('$set' => array("try" => 3)),
    
"upsert" => true,
);

$batch = new MongoUpdateBatch($collection);
$batch->add($item1);
$batch->add($item2);
$batch->add($item3);
$batch->execute(array("w" => 1));

?>

Example #3 MongoWriteBatch::add() example

Batching up multiple delete operations

<?php
$mc 
= new MongoClient("localhost");
$collection $mc->selectCollection("test""test");


$item1 = array(
    
"q" => array("my" => "demo"),
    
"limit" => 1,
);
$item2 = array(
    
"q" => array("try" => 3),
    
"limit" => 1,
);


$batch = new MongoDeleteBatch($collection);
$batch->add($item1);
$batch->add($item2);
$batch->execute(array("w" => 1));
?>

MongoWriteBatch
PHP Manual