[英]Update document in MongoDB with Java
I'm using MongoDB 3.2 and MongoDB Java Driver 3.2. 我正在使用MongoDB 3.2和MongoDB Java驱动程序3.2。 I want to update the value the document having its ID.
我想更新具有其ID的文档的值。 In order to do that I tried to use the following two approaches (found in Stackoverflow and MongoDB Blog ):
为了做到这一点,我尝试使用以下两种方法(可在Stackoverflow和MongoDB Blog中找到 ):
Approach #1: 方法1:
for(String docID : expiredDocsIDs) {
Bson filter = Filters.eq("_id", docID);
Bson updates = Updates.set("isExpired", true);
dbCollection.findOneAndUpdate(filter, updates);
}
Approach #2: 方法2:
expiredDocsIDs.stream()
.forEach(docID -> {
BasicDBObject searchQuery = new BasicDBObject("_id", docID);
BasicDBObject updateFields = new BasicDBObject();
updateFields.append("isExpired", true);
updateFields.append("fetchStatus", "FETCHED");
BasicDBObject setQuery = new BasicDBObject();
setQuery.append("$set", updateFields);
dbCollection.updateOne(searchQuery, setQuery);
});
None of these approaches does not work. 这些方法都不行。 It iterates over the list of documents IDs, executes the code but at the end of the code, when I check the documents in DB there is no any change in the documents' field I tried to update.
它遍历文档ID列表,执行代码,但是在代码末尾,当我检查DB中的文档时,我尝试更新的文档字段中没有任何更改。
My question: 我的问题:
How can I update the specific document in MongoDB? 如何在MongoDB中更新特定文档?
As BlakesSeven correctly noted, the problem was with a casting of _id
field. 正如BlakesSeven正确指出的那样,问题出在
_id
字段的转换上。 The original code sent this parameter as String
while the correct way is to send a parameter of ObjectId
type. 原始代码将此参数作为
String
发送,而正确的方法是发送ObjectId
类型的参数。
The correct and worked code form MongoDB
3.2: 正确且有效的代码格式
MongoDB
3.2:
this.trackedEpisodesReg.entrySet().stream()
.filter(ep -> ep.getValue().isExpired())
.forEach(ep -> {
BasicDBObject updateFields = new BasicDBObject();
updateFields.append("isExpired", true);
BasicDBObject setQuery = new BasicDBObject();
setQuery.append("$set", updateFields);
BasicDBObject searchQuery = new BasicDBObject("_id", new ObjectId(ep.getValue().getEpisodeID()));
dbCollection.updateOne(searchQuery, setQuery);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.