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

时间:2014-10-19 09:34:28

标签: mongodb spring-data-mongodb

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

mongoOperations.save(theObject, <fields to ignore>)

据我所知,最近推出的 @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);
}

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

1 个答案:

答案 0 :(得分:0)

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

  

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

相关问题