我正在使用 MongoDB 3.2 和 MongoDB Java 驱动程序 3.2。为了更新文档,我使用以下代码:
unfetchedEpisodes.stream()
.forEach(ep -> {
BasicDBObject updatedFields = new BasicDBObject();
updatedFields.append("fetchStatus", "IN_PROCESS");
updateColFields(updatedFields, dbCollection, new ObjectId(ep.get("_id").toString()));
});
public void updateColFields(BasicDBObject updatedFields, MongoCollection<Document> dbCollection, ObjectId docID) {
BasicDBObject setQuery = new BasicDBObject();
setQuery.append("$set", updatedFields);
BasicDBObject searchQuery = new BasicDBObject("_id", docID);
dbCollection.updateOne(searchQuery, setQuery);
}
此代码有效,但我不确定此代码仅更新文档的特定字段(例如fetchStatus
),而不是覆盖整个文档。
这段代码是仅更新文档的特定字段还是简单地覆盖整个文档?
最佳答案
它只是更新指定的字段。如果该字段不存在,则会创建该字段。其他领域保持不变。根据documentation :
The $set operator replaces the value of a field with the specified value.
和
If the field does not exist, $set will add a new field with the specified value, provided that the new field does not violate a type constraint. If you specify a dotted path for a non-existent field, $set will create the embedded documents as needed to fulfill the dotted path to the field.
关于java - 使用 Java 更新 MongoDB 中的特定字段而不是整个文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35843111/