繁体   English   中英

Java mongodriver 3.4.9使用$ inc和$ sum运算符更新字段的最简单方法是什么

[英]Java mongodriver 3.4.9 what is the easiest way to use $inc and $sum operators to update a field

我正在为我的Java应用程序使用mongodb,并且陷入了这个问题,我想用Java语言转换mongo操作,但是我找不到解决方案。 Mongo操作是:

$ inc:

db.products.update(
   { _id: "someId" },
   { $inc: { quantity: +2 } }
)

$ sum:

db.students.aggregate([
   {
     $group: {
       value: { $sum: valueToAdd},
     }
   }
])

到目前为止,这就是我的结果,但是仍然无法正常工作。

Bson filter = Filters.eq("_id", someId);
UpdateOptions options = new UpdateOptions().upsert(true);   
Bson incrementFirstTry = new Document("$inc", new Document().append("quantity", 2));
Bson incrementSecondTry = new Document("quantity", +2);
Bson sumFirstTry = new Document("$sum", new Document("value", valueToAdd))
Bson sumSecondTry = Aggregates.group(someId, Accumulators.sum("value", valueToAdd));

collection.updateOne(filter, incrementFirstTry, options);
collection.updateOne(filter, incrementSecondTry, options);
collection.updateOne(filter, sumFirstTry, options);
collection.updateOne(filter, sumSecondTry, options);

两者在递增时都表示数量是一个字符串,因此无法将其加到整数中。

使用$ sum时,它要么说:com.mongodb.MongoWriteException:未知修饰符:$ group或com.mongodb.MongoWriteException:未知修饰符:$ sum

我知道我尝试过的不是很正确,但是我不知道如何解决。

两个问题:

  1. 如果我不得不猜测,我会说您的products表中的quantity字段以某种方式在quantity字段中输入了一个字符串。 incrementFirstTry看起来不错; incrementSecondTry没有按照您的想法去做。 它只是将字段设置为正2,而不是将其递增2。

  2. 您缺少$group语句中的_id字段。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM