Not seeing your attempts to solve this in PHP, much of what follows is based on assumptions and therefore cannot offer a better solution, but nevertheless will serve as a guide in order to influence you in the right direction to solve your problem.
Using the PHP driver with the free mongo-php-library , which implements a more fully functional API on top of the bare-bones driver, build an aggregation pipeline and the subsequent bulk update operation as
$pipeline = [["$project" => ["data1" => 1, "data2" => ["$concat" => [ "$data1", " ", "$data2" ]]]]]; $operation = new Aggregate($databaseName, $collectionName, $pipeline, ['typeMap' => $typeMap]); $cursor = $operation->execute($primaryServer); $results = iterator_to_array($cursor); function mapper($doc) { return [ "updateOne" => [ ["_id" => $doc["_id"]], [ "$set" => [ "data2" => $doc["_id"] ] ] ] ] }; $ops = array_map("mapper", $results); $bulkUpdateOps = new BulkWrite($databaseName, $collectionName, $ops); $writeResult = $bulkUpdateOps->execute($primaryServer);
In the above example, $primaryServer is a parameter for BulkWrite execute() , which should contain an instance of the MongoDB\Driver\Server object, i.e. your basic MongoDB server connection details. The $typeMap is an optional parameter in the Aggregate() constructor to indicate the type map for BSON deserialization. This will be applied to the returned cursor.
If you are using an outdated driver, then run the following operation, which uses the API for bulk operations , which is available from MongoDB> = 2.6 <= 3.0:
$client = new MongoClient(); $collection = $client->selectCollection("database", "collection"); $pipeline = array( array( "$project" => array( 'data1' => 1, "data2" => array("$concat" => array( "$data1", " ", "$data2" )) ) ) ); $batch = new MongoUpdateBatch($collection); $counter = 0; foreach ($collection->aggregate($pipeline) as $doc ) { $batch->add( array( "q" => array( '_id' => $doc['_id'] ), "u" => array( '$set' => array( "data2" => $doc["data2"] ) ) ) ); $counter++; if ($counter % 500 === 0) { $retval = $batch->execute(array( 'w' => 1)); $counter++; $batch = new MongoUpdateBatch($collection); } } if ($counter > 0) { $retval = $batch->execute(array( 'w' => 1 )); }