使用 Java 更新 MongoDB 中的特定字段而不是整个文档

Update the specific field and not the whole document in MongoDB with Java

我正在使用 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.