How to query a Collection
MongoDB is a scalable, high-performance, open source NoSQL database.
It offers Ad hoc queries, Indexing, Replication, Load balancing, File storage (GridFS), Aggregation,
MapReduce and Server-side JavaScript execution.
This requires the library mongo-2.8.0.jar to be present in the classpath.
The following example shows how to query a collection.
package com.bethecoder.tutorials.mongodb.tests;
import java.net.UnknownHostException;
import com.mongodb.BasicDBObject;
import com.mongodb.BasicDBObjectBuilder;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.Mongo;
import com.mongodb.MongoException;
public class QueryTest {
/**
* @param args
*/
public static void main ( String [] args ) {
try {
//Connect to mongoDB with given IP and PORT
Mongo mongo = new Mongo ( "localhost" , 27017 ) ;
//Get the database object
DB database = mongo.getDB ( "mytestdb" ) ;
//Gets a collection with a given name.
DBCollection collection = database.getCollection ( "mynums" ) ;
//Query for (num > 2 && num < 9) && (even==true)
DBObject query = new BasicDBObject () ;
query.put ( "num" , BasicDBObjectBuilder.start () .add ( "$gt" , 2 ) .add ( "$lt" , 9 ) .get ()) ;
query.put ( "even" , true ) ;
//Queries for all objects in this collection
DBCursor dbCursor = collection.find ( query ) ;
DBObject record = null ;
while ( dbCursor.hasNext ()) {
record = dbCursor.next () ;
System.out.println ( record ) ;
}
} catch ( UnknownHostException e ) {
e.printStackTrace () ;
} catch ( MongoException e ) {
e.printStackTrace () ;
}
}
}
It gives the following output,
{ "_id" : 4 , "num" : 4 , "even" : true , "num^2" : 16.0}
{ "_id" : 6 , "num" : 6 , "even" : true , "num^2" : 36.0}
{ "_id" : 8 , "num" : 8 , "even" : true , "num^2" : 64.0}