Question

Is there anyway i can do $each on Update.addToSet() on spring mongodb ?

Currently when i pass the array object as the addToSet param, it's only using $addToSet without the $each, resulting in putting the passed array into the existing array.

Was it helpful?

Solution

I've got a working version of a custom Update class, mixed with the solution proposed in https://jira.springsource.org/browse/DATAMONGO-471

public class MyUpdate extends Update {
    public MyUpdate myAddToSet(String key, Object value, MongoOperations ops) {
        BasicDBObject dbObject = new BasicDBObject();
        ops.getConverter().write(value, dbObject);
        this.addToSet(
            key,
            dbObject
        );
        // dont do this, will cause serialization exception
//      System.out.println(this.getUpdateObject().toString());
        return this;
    }
    public MyUpdate myAddToSetAll(String key, Collection<Object> values, MongoOperations ops) {
        BasicDBList eachList = new BasicDBList();
        for (Object value : values) {
            BasicDBObject dbObject = new BasicDBObject();
            ops.getConverter().write(value, dbObject);
            eachList.add(dbObject);
        }
        this.addToSet(
            key,
            BasicDBObjectBuilder.start("$each", eachList).get()
        );
        // dont do this, will cause serialization exception
//      System.out.println(this.getUpdateObject().toString());
        return this;
    }

    public MyUpdate myPushAll(String key, Object[] values) {
        super.addMultiFieldOperation("$pushAll", key, values);
        return this;
    }
    public MyUpdate myPush(String key, Object[] values) {
        super.addMultiFieldOperation("$push", key, values);
        return this;
    }
    public MyUpdate myPush(String key, Object value) {
        super.addMultiFieldOperation("$push", key, value);
        return this;
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top