mongodb如何批量修改内嵌文档的属性?
PHPz
PHPz 2017-04-25 09:02:17
0
4
813
{
  "_id" : ObjectId("52fb2ceb1e2f8622d4228a7a"),
  "from" : 0,
  "message" : [{
      "data" : "test1",
      "status" : true,
      "time" : 1
    }, {
      "data" : "test2",
      "status" : true,
      "time" : 2
    }],
  "to" : 1,
  "type" : "s"
}

如何用一条命令把message数组中2个对象元素中的status属性都改成false?

是否只能在客户端做逻辑处理:

var cursor =  db.msg.find({“to”: uid, “message.status”: false});
while(cursor.hasNext()){  //由于默认情况下find取得的游标已经做过快照,所以理论上不会影响在find之后新增的数据
    var doc = cursor.next();
    var from = doc.from;
    var type = doc.type;
        //循环对应文档的message数组中的所有元素,进行逐行更改
    item.message.foreach(function(msg){
         db.msg.update({
                “to”: uid,
                “from”: from,
                “type”: type,
                “message.time”: msg.time
            },
            {
                “$set”: {
                        “message.$.status”: true    
                    }
                }
            );
        });
}

请大家指正~~

PHPz
PHPz

学习是最好的投资!

reply all(4)
滿天的星座

You can also change it in the mongo shell.

Peter_Zhu
var true_metadata = db.modulestore.find({"metadata.tabs": {$exists: true}})
var updated_tabs = [];

true_metadata.forEach(function(item){
    var tabs = item.metadata.tabs
    if (item && item.metadata && tabs ){
        tabs.forEach(function(item){
            if(item.type == "wiki") {
                item.name = "资料";
            }
        })

    db.modulestore.update({"_id": item._id}, {$set: {
            "metadata.tabs": tabs 
    }})

    updated_tabs.push(tabs)
 }
})

updated_tabs

I also encountered a similar problem. I checked the official documentation. My local solution is as above. I hope it can help you

迷茫

Use the aggregation framework aggregate to do it. Unwind it first with unwind. Then update all status.

phpcn_u1582

This can be done, mongodb provides a dollar sign "$" to update embedded data objects.
If you want the result, you can write the following statement:

    db.test.update({_id:ObjectId("52fb2ceb1e2f8622d4228a7a"), "message.status":true}, 
        {$set:{"message.$.status":false}})

But please note that your update conditional statement must include the condition of the object in the data. For example, {"messaage.status":true} above, you can also change it to something else.

Please refer to the mongodb documentation: http://docs.mongodb.org/manual/reference/operator/update/positional/#update-documents-in-an-array

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template