在 MongoDB 中的子文档中增加值

Increment value in a subdocument in MongoDB

我的 collection

中有一个文档
{
    "_id" : ObjectId("59bd65b281a24497a0b3b401"),
    "user_id" : "1",
    "is_placed" : false,
    "items" : [ 
        {
            "product_id" : 1,
            "units" : 0
        }, 
        {
            "product_id" : 2,
            "units" : 0
        }
    ]
}

我想为 product_id = 1 增加 'units' 的值。这是我的代码的样子:

        MongoClient mongoConnection = new MongoClient("localhost", 27017);

    try {
        MongoDatabase db = mongoConnection.getDatabase("mydb");
        MongoCollection<Document> collection = db.getCollection("orders");
        BasicDBObject whereQuery = new BasicDBObject();
        whereQuery.put("user_id", "1");
        whereQuery.put("is_placed", false);
        whereQuery.put("product_id", 1);
        BasicDBObject incValue = new BasicDBObject("items.units", 1);
        BasicDBObject intModifier = new BasicDBObject("$inc", incValue);
        collection.updateOne(whereQuery, intModifier);
    } catch (Exception e) {
        e.printStackTrace();
    }

它不会抛出任何错误。但它也不会增加价值。我如何实现它?此外,是否可以仅在存在 product_id = 1 的情况下增加它,否则将 product_id = 1?

要更新数组中的嵌入文档,您应该使用 $ operator。我看不到您在代码中的任何地方使用它。你的代码可能,应该是这样的:

MongoClient mongoConnection = new MongoClient("localhost", 27017);

try {
    MongoDatabase db = mongoConnection.getDatabase("db");
    MongoCollection<Document> collection = db.getCollection("orders");
    BasicDBObject whereQuery = new BasicDBObject();
    whereQuery.put("user_id", "1");
    whereQuery.put("is_placed", false);
    whereQuery.put("items.product_id", 1);
    BasicDBObject incValue = new BasicDBObject("items.$.units", 1);
    BasicDBObject intModifier = new BasicDBObject("$inc", incValue);
    collection.updateOne(whereQuery, intModifier);
} catch (Exception e) {
    e.printStackTrace();
}