【问题标题】:Update MongoDB field using value of another field in PHP使用 PHP 中另一个字段的值更新 MongoDB 字段
【发布时间】:2021-09-02 07:32:59
【问题描述】:

在 MongoDB PHP 中,是否可以使用来自另一个字段的值来更新一个字段的值?

下面的 Mongo Shell 命令运行良好。字段"product_name" 的值正在更新为字段"product_name_copy"。

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

但是,当我在 PHP 中使用这段代码时, PHP 代码:

$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);

遇到这个错误

注意:未定义变量:product_name in C:\xampp\htdocs\mongo\mongo-update.php 第 10 行

如果我用单引号代替双引号,

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

相同的值 $product_name 正在更新到字段 "product_name_copy",如下所示。

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

有人知道这个问题的解决方案吗?

【问题讨论】:

    标签: php mongodb mongodb-query


    【解决方案1】:

    我终于找到了解决办法。

    我们需要将 '$set' 数组放入另一个数组中以进行字段值更新。

    PHP 代码:

    $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);
    

    以上代码的输出是

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

    这正是我想要的。

    【讨论】:

      猜你喜欢
      • 2011-04-27
      • 2020-06-12
      • 1970-01-01
      相关资源
      最近更新 更多