My Adventures in Coding

March 7, 2010

MongoDB queries in Java using Conditional Operators

Filed under: Java,NOSQL — Brian @ 4:29 pm
Tags: , , , ,

When I first started using MongoDB, I used the interactive shell to learn the query syntax. The syntax is simple and straightforward. However, when I started using the Java driver I was not sure how to translate some of my command line queries into Java code, for example some of the conditional operators like “$in”. The Java documentation on the MongoDB website only showed how to use some basic conditionals like greater than and less than, but not for using other conditionals that use lists like the $in option.

A simple query for all cars with the make “Ford” that match any of several models listed:


SELECT * FROM dbo.Cars 
WHERE make="Ford" 
AND model IN ("Galaxy","Mustang","Meteor")

MongoDB interactive shell: { "make":"Ford", "model":{ $in: ["Galaxy","Mustang","Meteor"] } } )

MongoDB Java driver:

BasicDBObject query = new BasicDBObject();
query.put("make", "Ford");
String models[] = new String[]{"Galaxy", "Mustang", "Meteor"};
query.put("model", new BasicDBObject("$in", models));
DBCursor resultsCursor = carsCollection.find(query);


  1. Hello Brian!

    Thank you for the post, it’s useful. You’re right, unfortunately the Java documentation on the MongoDB website shows only some basics.
    Did you try to use more complicated queries such as GROUP BY and COUNT with Java driver?

    Best wishes,

    Comment by Tatiana — April 7, 2010 @ 10:47 am | Reply

    • Great, I am glad the post was useful! Since that post we have shifted to using Python for our code that directly interacts with MongoDB, so I have not had much opportunity lately to play around more with the Java Driver. So far I am really enjoying my MongoDB experience!


      Comment by Brian — April 7, 2010 @ 2:18 pm | Reply

  2. […] I must first define a query (aka view) and then expose it to the outside world. In contrast, MongoDB works much like you’ve been used to with normal databases: you can query for what ever your heart desires at […]

    Pingback by MongoDB and CouchDB: vastly different queries | The Disco Blog — September 1, 2010 @ 1:51 pm | Reply

  3. For more examples on comparison and logical operators : –

    Comment by saurav jain — April 16, 2014 @ 8:57 pm | Reply

RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

Create a free website or blog at

%d bloggers like this: