Alex
Alex

Reputation: 201

spring-data mongodb exclude fields from update

How to make sure that specific fields can be inserted upon creation, but can optionally be excluded when updating the object. I'm essentially looking for something like the following:

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

From what I see, recently introduced @ReadOnlyProperty will ignore the property both for 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 issue is that now it will use Mongo $set form of updates for everything, not just for specific cases. Please advise if there is any simpler (and correct) way to achieve this.

Upvotes: 8

Views: 2916

Answers (1)

Rajat Goel
Rajat Goel

Reputation: 2305

While creating an update object, use $setOnInsert instead of $set. It is available in spring mongo as well.

If an update operation with upsert: true results in an insert of a document, then $setOnInsert assigns the specified values to the fields in the document. If the update operation does not result in an insert, $setOnInsert does nothing.

Upvotes: 1

Related Questions