增加MongoDB子文档中的值

时间:2017-09-16 19:21:13

标签: java mongodb mongodb-query mongodb-java

我的藏品中有一份文件

{
    "_id" : ObjectId("59bd65b281a24497a0b3b401"),
    "user_id" : "1",
    "is_placed" : false,
    "items" : [ 
        {
            "product_id" : 1,
            "units" : 0
        }, 
        {
            "product_id" : 2,
            "units" : 0
        }
    ]
}

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

        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

1 个答案:

答案 0 :(得分:2)

要更新数组中的嵌入文档,您应该使用$ 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();
}