1

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.?

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

I tried this method and it is producing an error complaining wrong type array ` BSON field 'update.updates.u' is the wrong type 'array', expected type 'object', type: MongoDB\Driver\Exception\BulkWriteException`
Can you share your code for clear understanding of your issue.?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.