Mongodb Java 在文档中添加新数组元素

Mongodb Java add new array element in document

我正在使用 mongo 2.2.3 和 java 驱动程序。我的困境是,我必须将一个字段和值 $push 到一个数组元素中,但我似乎无法弄清楚如何做到这一点。我的数据样本:

"_id" : 1,
"scores" : [
    {
        "type" : "english",
        "score" : 78.97979
    },
    {
        "type" : "spanish",
        "score" : 6.99
    }
]

我想在 type = english.

的文档中推送一个数组 attribute ("grade" : "A")

推送后的文档如下所示:

"_id" : 1,
    "scores" : [
        {
            "type" : "english",
            "score" : 78.97979,
            "grade" : "A"
        },
        {
            "type" : "spanish",
            "score" : 6.99
        }
    ]

我尝试使用 shell :

db.Sample.update({"scores.type" : "english"},{"$push" : {"scores": {"grade":"A"}}})

但这不是在特定位置添加属性。

使用 Set 尝试此更新并参考:

db.Sample.update({"scores.type" : "english"},{"$set" : {"scores.$.grade":"A"}})