spring-data mongodb从更新中排除字段

Ale*_*lex 7 mongodb spring-data-mongodb

如何确保在创建时可以插入特定字段,但可以选择在更新对象时将其排除.我基本上是在寻找以下内容:

mongoOperations.save(theObject, <fields to ignore>)
Run Code Online (Sandbox Code Playgroud)

从我看来,最近推出的@ReadOnlyProperty将忽略插入和更新的属性.

通过实现我的Custom MongoTemplate并覆盖其doUpdate方法,我能够获得所需的行为,如下所示:

@Override
protected WriteResult doUpdate(String collectionName, Query query,
        Update originalUpdate, Class<?> entityClass, boolean upsert, boolean multi) {

    Update updateViaSet = new Update();

    DBObject dbObject = originalUpdate.getUpdateObject();
    Update filteredUpdate = Update.fromDBObject(dbObject, "<fields to ignore>");

    for(String key : filteredUpdate.getUpdateObject().keySet()){

        Object val = filteredUpdate.getUpdateObject().get(key);

        System.out.println(key + "::" + val);

        updateViaSet.set(key, filteredUpdate.getUpdateObject().get(key));
    }

    return super
            .doUpdate(collectionName, query, updateViaSet, entityClass, upsert, multi);
}
Run Code Online (Sandbox Code Playgroud)

但问题是,现在它将使用Mongo $ set形式的更新,而不仅仅是针对特定情况.请告知是否有更简单(和正确)的方法来实现这一目标.

Raj*_*oel 1

创建更新对象时,使用 $setOnInsert 而不是 $set。它在 spring mongo 中也可用。

如果使用 upsert: true 的更新操作导致插入文档,则 $setOnInsert 会将指定的值分配给文档中的字段。如果更新操作未导致插入,则 $setOnInsert 不执行任何操作。