Query fields in a MongoDB Collection.

You can use get on the returned document by the cursor to get the field you are looking for. Like this:

System.out.println(cursor.next().get("key"));

I know you already accepted an answer, but it isn't exactly what you were asking for.

Here is some working code:

// get Mongo set up...
Mongo m = new Mongo();
DB db = m.getDB( "test" );
DBCollection coll = db.getCollection("test");

// insert a test record
coll.insert(new BasicDBObject("Name","Wes").append("x", "to have a second field"));

// create an empty query
BasicDBObject query = new BasicDBObject(); 
// configure fields to be returned (true/1 or false/0 will work)
// YOU MUST EXPLICITLY CONFIGURE _id TO NOT SHOW
BasicDBObject fields = new BasicDBObject("Name",true).append("_id",false);

// do a query without specifying fields (and print results)
DBCursor curs = coll.find(query);
while(curs.hasNext()) {
   DBObject o = curs.next();
   System.out.println(o.toString());
}

// do a query specifying the fields (and print results)
curs = coll.find(query, fields);
while(curs.hasNext()) {
   DBObject o = curs.next();
   System.out.println(o.toString());
}

The first query outputs:

{ "_id" : { "$oid" : "4f5a6c1603647d34f921f967"} , "Name" : "Wes" , "x" : "to have a second field"}

And the second query outputs:

{ "Name" : "Wes"}

Take a look at DBCollection.find

BasicDBObject query = new BasicDBObject(); // because you have no conditions
BasicDBObject fields = new BasicDBObject("Name",1);
coll.find(query, fields);

Tags:

Java

Mongodb