【问题标题】:Multi update with $set and php Mongo使用 $set 和 php Mongo 进行多重更新
【发布时间】:2017-07-03 07:23:02
【问题描述】:

我正在尝试在 mongolab 平台上使用带有 multi=true 参数的 update() 函数更新集合中的多个项目。 问题是仅更新集合中的第一项

收藏:

{
    "_id": {
        "$oid": "5454b446e4b02a012c939a0a"
    },
    "value": "1234",
    "name": "first"
},
{
    "_id": {
        "$oid": "5454b446e4b02a012c939a0a"
    },
   "value": "1234",
   "name": "second"
}

脚本代码:

$db->collection->update(
    array('value' => '1234'),
    array('$set' => array(
        'name' => 'example name',
    )),
    array('multi' => true)
);

结果:

{
    "_id": {
        "$oid": "5454b446e4b02a012c939a0a"
    },
    "value": "1234",
    "name": "example name"
},
{
    "_id": {
        "$oid": "5454b446e4b02a012c939a0a"
    },
   "value": "1234",
   "name": "second"
}

update() 函数只接受三个数组作为参数。

【问题讨论】:

  • 手册是你的朋友。检查正确的语法。
  • 用“multiple”=>“true”而不是“multi”解决。来源:stackoverflow.com/questions/7934119/…
  • @Hadokee,请将其添加为您问题的答案。

标签: php mongodb mlab nosql


【解决方案1】:



嗨,Yogesh,
我认为您的查询应该是:

db.collectionName.update({"value":"1234"},{$set:{"name":"example name"}},{'upsert':true, 'multiple': true});

相应的 PHP 代码为:

<?php
    $m = new MongoClient(); //connects to local mongo

    $db_name = 'ri'; //replace database name you want to work with
    $collection_name = 'brand_graph'; //replace collection name you want to work with

    $select = $m->selectDB($db_name)->selectCollection($collection_name);

    $where_array = array(
        'value' => 1234
    );

    $update_data = array(
        '$set' => array(
            'name' => 'example name'
        )
    );

    $options = array(
        'upsert' => true,
        'multiple' => true
    );


    $select->update($where_array, $update_data, $options);
?>

我希望这就是你想要的。

【讨论】:

    【解决方案2】:

    我在下面写了更新多个文档的 mongo 查询,但是,我不知道如何在 PHP 代码中转换它,但作为参考,你应该使用这个查询

     db.collectionName.update({"value":"1234"},{$set:{"name":"example name"}},true,true)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-07-15
      • 2021-12-14
      • 1970-01-01
      • 2023-03-25
      • 2017-10-10
      • 1970-01-01
      • 2021-07-15
      • 2018-10-15
      相关资源
      最近更新 更多