【问题标题】:PHP MongoDB update doesn't workPHP MongoDB 更新不起作用
【发布时间】:2015-02-12 07:52:34
【问题描述】:
{
    "__v" : 2,
    "_id" : ObjectId("54dc4fd10ac1f6a066a0646c"),
    "desc" : "test1",
    "lists" : [ 
        {
            "index" : 1,
            "text" : "__point",
            "_id" : ObjectId("54dc4fda0ac1f6a066a0646d"),
            "createdAt" : ISODate("2015-02-12T07:01:46.390Z")
        }, 
        {
            "index" : 2,
            "text" : "__point",
            "_id" : ObjectId("54dc4fdd0ac1f6a066a0646e"),
            "createdAt" : ISODate("2015-02-12T07:01:49.668Z")
        }
    ],
    "name" : "test" }

测试数组如下所示。我想在检查_id的列表中添加“类别”字段并添加值“0”。

我试过了

$collection->update(array('_id' => new MongoId("54dc4fd10ac1f6a066a0646c")),array('$set' => array(new MongoId("54dc4fda0ac1f6a066a0646d").".lists.category" => '0')));

像这样,但它不起作用。

【问题讨论】:

标签: php mongodb


【解决方案1】:
set third parameter of update to true.
i think there is some problem in finding which embedded document for updated.
try this one might be work.
$collection->update(array('_id' => new MongoId("54dc4fd10ac1f6a066a0646c"), 'lists._id' => "54dc4fda0ac1f6a066a0646d"), array('$set' => array("lists.$.category" => '0')), true);

【讨论】:

    【解决方案2】:

    您好,我对 PHP 不太了解,但您可以通过以下脚本进行操作

        db.collectionName.find({
        "lists": {
        "$exists": true
        }
    }).forEach(function(data){
        for(vari=0;i<data.lists.length;i++){
        db.collectionName.update({
            "_id": data._id,
            "lists.index": data.lists[
                i
            ].index
        },
        {
            "$set": {
                "lists.$.category": 0
            }
        },
        true,
        true);
        }
    })
    

    【讨论】:

      猜你喜欢
      • 2016-09-28
      • 1970-01-01
      • 2014-08-24
      • 2018-08-15
      • 2014-07-05
      • 1970-01-01
      • 1970-01-01
      • 2013-01-11
      • 1970-01-01
      相关资源
      最近更新 更多