Spring -data mongodb exclude fields from update

How to make sure that certain fields can be inserted at creation, but can be excluded when updating the object if desired. Essentially, I'm looking for something like the following:

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

From what I see, the recently introduced @ReadOnlyProperty will ignore the property for both inserts and updates.

I was able to get the desired behavior by implementing my Custom MongoTemplate and overriding its doUpdate method as follows:

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

But the problem is that now he will use the Mongo $ installation form of updates for everything, and not just for specific cases. Please advise if there is any simpler (and correct) way to achieve this.

+7
1

$ setOnInsert $ set. .

upsert: true , $ setOnInsert . , $ setOnInsert .

0

All Articles