Can't append to array using string field name [$] when performing update on array fields

和自甴很熟 提交于 2020-01-11 05:04:39

问题


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

An example schema is below:

{
    "_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)

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)

However I get the error:

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

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


回答1:


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


来源:https://stackoverflow.com/questions/13040344/cant-append-to-array-using-string-field-name-when-performing-update-on-arra

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!