MongoDB定位运算符$ [英] MongoDB Positional Operator $

查看:70
本文介绍了MongoDB定位运算符$的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我收到了以下文件

{
    _id : 91,
    "myArray" : [ 
        {
            "a" : "1",
            "b" : true
        }, 
        {
            "a" : "1",
            "b" : true
        }, 
        {
            "a" : "1",
            "b" : true
        }
    ]
}

现在我想将每个myArray.b元素更新为false,其中btrue.所以我正在运行以下查询:

And now I want to update each myArray.b element to false where b is true. So I am running following query:

db.MyDB.update({"arr.b" : true},{$set : {"arr.$.b":false}},false, true)

我只得到第一个数组元素,而不是所有子文档的更新.

And I am getting just first array element updated not all subdocuments.

{
        _id : "91",
        "myArray" : [ 
            {
                "a" : "1",
                "b" : false
            }, 
            {
                "a" : "1",
                "b" : true
            }, 
            {
                "a" : "1",
                "b" : true
            }
        ]
    }

所有符合arr.b:true标准的子文档都应更新为arr.b = false. 根据来自MongoDB大学的视频,这种情况是可能的.

All sub-documents that match the arr.b:true criteria should be updated to arr.b = false. According to this video from MongoDB university this situation is possible.

我不想使用JavaScript函数.

I don't want to use JavaScript function.

我缺少什么?谢谢

推荐答案

不幸的是,现在无法更新数组中的所有文档-请参见MongoDB JIRA票证

Unfortunately updating all documents in array is not possible now - see MongoDB JIRA ticket Use positional operator to update all items in an array.

您可以手动更新每个文档:

You can update each document manually:

db.MyDB.find({}).forEach(function(doc) { 
  doc.myArray.forEach(function(item) { 
     if (item.b === true) 
        item.b = false; 
  }); 

  db.MyDB.update({ "_id": doc._id }, { "$set": { "myArray": doc.myArray }});
});

这篇关于MongoDB定位运算符$的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆