MongoException multi update only works with $ operators

It is quite possible for the first MongoDB Official Logotime when you are working with Multiple documents update in MongoDB you might see this exception.
Exception in thread “main” com.mongodb.MongoException: multi update only works with $ operators
Complete Trace :

Exception in thread "main" com.mongodb.MongoException: multi update only works with $ operators
at com.mongodb.CommandResult.getException(
at com.mongodb.CommandResult.throwOnError(
at com.mongodb.DBTCPConnector._checkWriteError(
at com.mongodb.DBTCPConnector.say(
at com.mongodb.DBTCPConnector.say(
at com.mongodb.DBApiLayer$MyCollection.update(
at com.mongodb.DBCollection.update(
at com.mongodb.DBCollection.update(
at com.lotusmedia.mongo.MultipleDocumentUpdate.updateDocuments(
at com.lotusmedia.mongo.MultipleDocumentUpdate.main(

Reason behind this as you have enabled the multi flag (4th argument) of the update method(), that will take care of updating multiple documents matching search criteria. So, I am assuming you are having something like this in your code.

DBObject modifiedObject =new BasicDBObject();
modifiedObject.put("key", "value");		
someCollection.update(searchObject, modifiedObject,false,true);

If you notice the highlighted line , above mentioned MongoException:multi update only works with $ operators generated from their.
One reason that I can think for the above caused exception is it may be possible that some of your documents in your collection may not have the key for which you want to update the value ,so to bring out the consistency it is asking you to use the $ operators.
One of such operator that we can use here is $set ,so that it will update the requested value in all the documents and wherever this key is not present it will create a new key there and associate new value to it.
To get rid of this MongoException , use $set operator.

DBObject modifiedObject =new BasicDBObject();
modifiedObject.put("$set", new BasicDBObject().append("key", "value"));
someCollection.update(searchObject, modifiedObject,false,true);

This time it will work as intended.

Image Credits : http:://


Saurabh Jain

A Developer working on Enterprise applications ,Distributed Systems, Hadoop and BigData.This blog is about my experience working mostly on Java technologies ,NoSQL ,git , maven and Hadoop ecosystem.

Share and Enjoy

  • Facebook
  • Twitter
  • Delicious
  • LinkedIn
  • StumbleUpon
  • Add to favorites
  • Email
  • RSS
Add Comment Register

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>