Nagaraj Juro
Nagaraj Juro

Reputation: 109

Update MongoDB field using value of another field in PHP

In MongoDB PHP, is it possible to update the value of a field using the value from another field?

The below Mongo Shell Command is working fine. Value of a field "product_name" is updating to the field "product_name_copy".

db.products.update(
  {},
  [{ $set: {
    "product_name_copy": "$product_name"
  }}],
  { multi: true }
)

But, While Am using this code in PHP, PHP code :

$where = array();
$update = array('$set' => array("product_name_copy" => "$product_name"));
$options = array("multi" => true);
$bulkWrite = new MongoDB\Driver\BulkWrite;
$bulkWrite->update($where,$update,$options);
$updated    = $mongo->executeBulkWrite("$db_name.products", $bulkWrite);

Am getting this error

Notice: Undefined variable: product_name in C:\xampp\htdocs\mongo\mongo-update.php on line 10

If I used single quotes instead of double quotes,

$update = array('$set' => array("product_name_copy" => '$product_name'));

the same value $product_name is updating to the field "product_name_copy" like below.

{
        "_id" : ObjectId("602a291f0406011059006c15"),
        "product_id" : 15,
        "product_name" : "Test Product",
        "product_name_copy" : "$product_name"
}

Anyone know the solution for this problem.?

Upvotes: 1

Views: 753

Answers (1)

Nagaraj Juro
Nagaraj Juro

Reputation: 109

Finally I found the solution.

We need to put '$set' array into another one array for field value update.

PHP Code :

$where = array();
$update = array(array('$set' => array("product_name_copy" => '$product_name')));
$options = array("multi" => true);
$bulkWrite = new MongoDB\Driver\BulkWrite;
$bulkWrite->update($where,$update,$options);
$updated    = $mongo->executeBulkWrite("$db_name.products", $bulkWrite);

Output of the above code is

{
        "_id" : ObjectId("602a291f0406011059006c15"),
        "product_id" : 15,
        "product_name" : "Test Product",
        "product_name_copy" : "Test Product"
}

This is what I exactly wanted.

Upvotes: 2

Related Questions