How to query for only a certain attribute

Go To StackoverFlow.com

1

Suppose I want to query for only a certain attribute of all documents, something like in SQL:

SELECT FIRSTNAME
FROM TABLE1

How can I do it with Mongo and it's Java API?

2012-04-04 07:40
by Joly


1

In the Java API, you can do it like this. You have to explicitly turn off the _id field, in order to exclude it.

Mongo m = new Mongo();
DB db = m.getDB( "test" );

DBCollection coll = db.getCollection("test");       
coll.insert(new BasicDBObject("Name","Wes").append("x", "to have a second field"));
BasicDBObject query = new BasicDBObject(); 
BasicDBObject fields = new BasicDBObject("Name",1).append("_id",false);
DBCursor curs = coll.find(query, fields);

while(curs.hasNext()) {
  DBObject o = curs.next();
  System.out.println(o.toString());
}

Output:

{ "Name" : "Wes"}

Update for sort:

coll.insert(new BasicDBObject("Name","Wes").append("x", "to have a second field"));
coll.insert(new BasicDBObject("Name","Alex").append("x", "to have a second field"));
coll.insert(new BasicDBObject("Name","Zeus").append("x", "to have a second field"));
BasicDBObject query = new BasicDBObject(); 
BasicDBObject fields = new BasicDBObject("Name",1).append("_id",false);
BasicDBObject orderBy = new BasicDBObject("Name",1);
DBCursor curs = coll.find(query, fields).sort(orderBy);
while(curs.hasNext()) {
   DBObject o = curs.next();
   System.out.println(o.toString());
}

Gives:

{ "Name" : "Alex"}
{ "Name" : "Wes"}
{ "Name" : "Zeus"}
2012-04-04 08:32
by Eve Freeman
spot on, thanks - Joly 2012-04-04 08:48
I am also interested in sorting the results. I tried adding coll.find(query, fields).sort(fields); but it doesn't seem to do the tric - Joly 2012-04-04 08:53
You wouldn't want to use fields, because it has that _id:false in it. Added an update to show you how sort works - Eve Freeman 2012-04-04 13:41


2

If you want to get all documents, use an empty object as the first argument. With the second one you only get the field FIRSTNAME.

db.table1.find({}, {'FIRSTNAME': 1});

See the documentation on querying for more details.

2012-04-04 08:04
by Matthias
Ads