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

标签 java mongodb mongodb-query crud

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

相关文章:

java - 我如何用我的java计算器继续加法

java - "public void actionPerformed"中如何使用JLabel

java - Junit Testwatcher 跳过/忽略测试

php - 如何为 Mongo 副本集配置 RockMongo

node.js - 查找未邀请任何用户的用户

node.js - 返回重复结果的 Mongoose 查询

java - Eclipse org.eclipse.core.resources java.lang.NoClassDefFoundError : sun/misc/BASE64Encoder

javascript - express promise 链错误

mongodb - Mongo 组并推送 : pushing all fields

mongodb - Mongodb条件查询