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:
SQL:
SELECT * FROM dbo.Cars
WHERE make="Ford"
AND model IN ("Galaxy","Mustang","Meteor")
MongoDB interactive shell:
db.cars.find( { "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);
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,
Tatiana
Comment by Tatiana — April 7, 2010 @ 10:47 am |
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!
Brian
Comment by Brian — April 7, 2010 @ 2:18 pm |
[...] 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 |