使用$ set和php Mongo进行多次更新

时间:2014-11-02 15:45:09

标签: php mongodb mlab nosql

我正在尝试使用mongolab平台上的multi = true param的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()函数只接受三个数组作为参数。

2 个答案:

答案 0 :(得分:3)



嗨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);
?>

我希望这是你所寻找的。

答案 1 :(得分:0)

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

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