Java driver for MongoDB does not provide any utility classes that could help with building update queries. If you want
to create a query to update or increment field values, you usually have to use BasicDBObjectBuilder. This is intuitive
approach, but queries defined in such a way are quite hard to read and maintain.
Have a look at the MongoDB QueryBuilder which is a utility for creating search queries:
As you can see, the criteria declaration here is very clear, it is based on the builder pattern which is highly
applicable when it comes to creating objects that have an undefined number of parameters.
Let's build a utility for update operations that works the same as the QueryBuilder:
/** * The utility for creating update queries. */publicclassBuilder{/** * The update query. */privatefinalDBObjectquery;/** * Initializes the update builder. */publicBuilder(){query=newBasicDBObject();}/** * Sets the new value for the field. * * @param key field name * @param object value to set * @return Builder instance */publicBuilderset(finalStringkey,finalObjectobject){addToQuery(Operators.SET,key,object);returnthis;}/** * Increments the field by a specified value. * * @param key field name * @param value number value * @return Builder instance */publicBuilderinc(finalStringkey,finalintvalue){addToQuery(Operators.INC,key,value);returnthis;}/** * Deletes the field. * * @param key field name * @return Builder instance */publicBuilderunset(finalStringkey){addToQuery(Operators.UNSET,key,1);returnthis;}/** * Checks whether the builder is empty. * * @return true if the builder is empty, false otherwise */publicbooleanisEmpty(){returnquery.keySet().isEmpty();}/** * Creates the DBObject-based query to be used for update operations. * * @return the query instance */publicDBObjectget(){returnquery;}/** * Adds the operation to the query. * * @param operator update operator * @param key param to update * @param object value to set */privatevoidaddToQuery(finalStringoperator,finalStringkey,finalObjectobject){finalBasicDBObjectsubQuery=query.get(operator)!=null?(BasicDBObject)query.get(operator):newBasicDBObject();query.put(operator,subQuery.append(key,object));}}
1234567891011
/** * MongoDB keywords for update operations. */publicclassOperators{publicfinalstaticStringSET="$set";publicfinalstaticStringINC="$inc";publicfinalstaticStringUNSET="$unset";}