[英]How to update a specific value in a document in mongodb using java
What I am trying to do is very simple but I'm not sure why it's not working. 我想做的事情很简单,但是我不确定为什么它不起作用。 What I'm trying to do is query the database on _id, if it matches, then update a specific record in the document it found.
我要尝试的是在_id上查询数据库,如果匹配,则在找到的文档中更新特定记录。
BasicDBObject basic = new BasicDBObject();
basic.put("_id", id);
FindIterable<Document> cursor = collection.find(basic);
if(cursor == null){
Document tableEntry = new Document();
tableEntry.put("_id", id);
tableEntry.put("longitude", longitude);
tableEntry.put("latitude", latitude);
tableEntry.put("status", status);
collection.insertOne(tableEntry);
closeConnection();
}else{
for(Document doc : cursor){
doc.put("status", "full");
}
}
After running this and checking the database, it doesn't seem to update. 运行此程序并检查数据库后,它似乎没有更新。 I currently have 1 document in the database and it doesn't update that.
我目前在数据库中有1个文档,它不会更新它。 I am using the mongo java 3.4.2 driver.
我正在使用mongo java 3.4.2驱动程序。
You're using insertOne
, which will insert a new document. 您正在使用
insertOne
,它将插入一个新文档。 What you need to use a command that will update an existing document, such as findOneAndUpdate
. 使用将更新现有文档的命令所需要的,例如
findOneAndUpdate
。
If you use a command like findOneAndUpdate
, note that it takes two parameters. 如果使用诸如
findOneAndUpdate
类的命令,请注意它findOneAndUpdate
两个参数。 The first is a query that uniquely identifies the document you want to update. 第一个查询可唯一标识您要更新的文档。 The second is an object that tells how to update the document.
第二个对象告诉您如何更新文档。
For example, in that second parameter, you may want to pass something like: 例如,在第二个参数中,您可能想要传递类似以下内容的内容:
BasicDBObject updatedDocument = new BasicDBObject();
updatedDocument.append("$set", new BasicDBObject().append("longitude", longitude));
Mongo provides these API calls for updates: Mongo提供了以下API调用以进行更新:
findOneAndUpdate
- https://docs.mongodb.com/v3.2/reference/method/db.collection.findOneAndUpdate/ findOneAndUpdate
- https: findOneAndUpdate
update
- https://docs.mongodb.com/v3.2/reference/method/db.collection.update/ update
: //docs.mongodb.com/v3.2/reference/method/db.collection.update/ updateOne
- https://docs.mongodb.com/v3.2/reference/method/db.collection.updateOne/ updateOne
- https: updateOne
updateMany
- https://docs.mongodb.com/v3.2/reference/method/db.collection.updateMany/ updateMany
- https: updateMany
Refer also to What's the difference between findAndModify and update in MongoDB? 另请参阅MongoDB中的findAndModify和update之间有什么区别?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.