[英]How to Update a Value with MongoDB
I want to add 1 point to a user each time he does something. 我想在用户每次执行某操作时为其增加1分。 So, I did this to create the user if not found and give him 1 point.
因此,我这样做是为了创建用户(如果找不到)并给他1分。 I am stuck where I don't know how to update the value and add 1 point.
我被卡在不知道如何更新值并加1分的地方。
//Add One Point
Document memberdoc = new Document("Username", event.getAuthor().getName());
Document found = (Document) collection.find(memberdoc).first();
if (found == null){
memberdoc.append("Points", 1);
memberdoc.append("UserID", event.getAuthor().getId());
collection.insertOne(memberdoc);
membersDataHashMap.put(event.getAuthor().getId(), new MembersData(event.getAuthor().getName(), event.getAuthor().getId(), 1));
}else{
String id = found.getString("UserID");
int points = found.getInteger("Points");
membersDataHashMap.put(event.getAuthor().getId(), new MembersData(event.getAuthor().getId(),id,points + 1));
}
//End
您可以使用$ inc来增加值。
You need to use $inc
operator with updateOne
method of db.collection.
您需要将
$inc
运算符与db.collection.
updateOne
方法一起使用db.collection.
For more details have a look official documentation of mongodb 有关更多详细信息,请查看mongodb的官方文档
In your case you can use it in the else condition as follows: 在您的情况下,可以在else条件下使用它,如下所示:
//Add One Point
Document memberdoc = new Document("Username", event.getAuthor().getName());
Document found = (Document) collection.find(memberdoc).first();
if (found == null){
memberdoc.append("Points", 1);
memberdoc.append("UserID", event.getAuthor().getId());
collection.insertOne(memberdoc);
membersDataHashMap.put(event.getAuthor().getId(), new MembersData(event.getAuthor().getName(), event.getAuthor().getId(), 1));
}else{
String id = found.getString("UserID");
int points = found.getInteger("Points");
collection.updateOne(
eq("UserID", found.getString("UserID")),
new Document("$inc", new Document("Points", 1))
);
membersDataHashMap.put(event.getAuthor().getId(), new MembersData(event.getAuthor().getId(),id,points + 1));
}
//End
Focus on below part only: 仅关注以下部分:
collection.updateOne(
eq("UserID", found.getString("UserID")),
new Document("$inc", new Document("Points", 1))
);
Which will find the matching user and increment the column Points
by 1. Hope this will resolved your problem. 它将找到匹配的用户并将“
Points
”列增加1。希望这可以解决您的问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.