从 java 更新 BasicDbList 元素

update BasicDbList element from java

我有一个 BasicDbObject 如下所示:

{
    "_id" : ObjectId("57060562ea9bcdfgs50ffdc7"),
    "name" : "g3",
    "detaillist" : [
        {
            "code" : "123",
            "School" : "LDC",
            "Friend" : "Archana"
        },
        {
            "code" : "456",
            "School" : "FWS",
            "Friend" : "Prapth"
        }
    ]
}

如何从 Java (com.mongodb) 更新具有 "code" = "456" 的对象的 "school" 字段?

您需要在更新中使用 $set and the positional $ 运算符才能正确识别数组元素,因为它充当与查询匹配的第一个元素的占位符文件,和 数组字段必须作为查询文档的一部分出现:

Mongo Shell

db.collection.update(
    { "detailist.code": "456"},
    {
        "$set": { "detailist.$.School": "foo" }
    }
)

以下代码在 Java 中复制上述 mongo shell 查询:

public class JavaUpdateArrayElement {
    public static void main(String args[]) throws UnknownHostException {

        MongoClient mongo = new MongoClient();
        DB db = mongo.getDB("databaseName");

        DBCollection coll = db.getCollection("test");

        /*
            MONGO SHELL : 
            db.test.update(
                { "detailist.code": "456"},
                {
                    "$set": { "detailist.$.School": "foo" }
                }
            )
        */

        // build the query { "detailist.code": "456"}
        BasicDBObject query = new BasicDBObject("detailist.code", "456");

        // build the update document
        BasicDBObject data = new BasicDBObject();
        data.put("detailist.$.School", "foo");

        BasicDBObject update = new BasicDBObject();
        update.put("$set", data);

        // run the update operation
        coll.update(query, update);     

    }
}