Joly
Joly

Reputation: 3276

How to query for only a certain attribute

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?

Upvotes: 1

Views: 190

Answers (2)

Eve Freeman
Eve Freeman

Reputation: 33175

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"}

Upvotes: 1

Matthias
Matthias

Reputation: 7521

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.

Upvotes: 2

Related Questions