对数组字段执行更新时,无法使用字符串字段名称 [$] 附加到数组 [英] Can't append to array using string field name [$] when performing update on array fields

查看:42
本文介绍了对数组字段执行更新时,无法使用字符串字段名称 [$] 附加到数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

rows我正在尝试对记录数组中的每个字段执行 mongodb 更新.

rowsI am attempting to perform a mongodb update on each field in an array of records.

示例架构如下:

{
    "_id" : ObjectId("508710f16dc636ec07000022"),
    "summary" : "",
    "uid" : "ABCDEF",
    "username" : "bigcheese",
    "name" : "Name of this document",
    "status_id" : 0,
    "rows" : [
        {
            "score" : 12,
            "status_id" : 0,
            "uid" : 1
        },
        {
            "score" : 51,
            "status_id" : 0,
            "uid" : 2
        }
    ]
}

到目前为止,我已经能够执行这样的单个更新:

So far I have been able to perform single updates like this:

db.mycollection.update({"uid":"ABCDEF","rows.uid":1}, {$set:{"rows.$.status_id":1}},false,false)

但是,我正在努力了解如何执行将所有数组记录更新为 status_id 为 1 的更新(例如).

However, I am struggling as to how to perform an update that will update all array records to a status_id of 1 (for instance).

以下是我想象的它应该如何工作:

Below is how I imagine it should work:

db.mycollection.update({"uid":"ABCDEF"}, {$set:{"rows.$.status_id":1}},false,true)

但是我得到了错误:

无法使用字符串字段名称 [$] 附加到数组

can't append to array using string field name [$]

我已经尝试了很长一段时间,但没有运气.有什么指点吗?

I have tried for quite a while with no luck. Any pointers?

推荐答案

你不能对你正在寻找的数组元素进行那种通配符"更新.我认为你能做的最好的事情就是像这样同时设置每个元素的 status_id 值:

You can't do the sort of 'wildcard' update of array elements that you're looking for. I think the best you can do is simultaneously set each element's status_id value like this:

db.mycollection.update(
    {"uid":"ABCDEF"},
    {$set:{
        "rows.0.status_id":1,
        "rows.1.status_id":1
    }}, false, true);

这篇关于对数组字段执行更新时,无法使用字符串字段名称 [$] 附加到数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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