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);

Create a free website or blog at