简体   繁体   English

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

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

I'm using MongoDB 3.2 and MongoDB Java Driver 3.2. 我正在使用MongoDB 3.2和MongoDB Java驱动程序3.2。 In order to update the document I use the following code: 为了更新文档,我使用以下代码:

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);
}

This code works but I'm not sure that this code updates only the specific field (eg fetchStatus ) of the document and not overwrites the whole document. 该代码有效,但是我不确定该代码更新文档的特定字段 (例如fetchStatus ),并且不会覆盖整个文档。

My question: 我的问题:
Does this code update only the specific field of the document or simply overwrites the whole document ? 此代码是更新文档的特定字段还是仅覆盖整个文档

It just updates the specified field. 它只是更新指定的字段。 The field will be created if it doesn't exist. 如果该字段不存在,则将创建该字段。 Other fields remain untouched. 其他字段保持不变。 According to documentation : 根据文件

The $set operator replaces the value of a field with the specified value. $ set运算符用指定的值替换字段的值。

and

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. 如果该字段不存在,则$ set将添加具有指定值的新字段,前提是该新字段不违反类型约束。 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. 如果为不存在的字段指定点划线路径,$ set将根据需要创建嵌入的文档,以实现到该字段的点划线路径。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM