kozher
kozher

Reputation: 725

Mongodb Java - How to return restricted fields with find() or findOne()

With the driver Java Mongodb, I am looking for a way to return just restricted fields with a find() or findOne(). For example, I have a collection "people" with fields : "id", "name", "surname", "address", "city"... and I just want to return "name" and "surname"

I searched on the Web and I just found this example of code Java Mongodb : http://vsbabu.org/mt/archives/2010/03/02/simple_mongodbjava_example.html

Upvotes: 12

Views: 24819

Answers (4)

Gökhan Ayhan
Gökhan Ayhan

Reputation: 1299

This codes will handle your problem.(java driver 3.0.2)

 BasicDBObject fields = new BasicDBObject();
 fields.put("title", 1);
 DBCursor cursor = collection.find(new BasicDBObject(),fields).sort(new BasicDBObject("_id", 1));

Upvotes: 2

HungNM2
HungNM2

Reputation: 3425

this code run for me:

String json = "{_id:0,name:1,surname:1}";
Bson bson =  BasicDBObject.parse( json );
FindIterable<Document> iterDoc = collection.find().projection(bson);

Upvotes: 1

seb
seb

Reputation: 818

If you are using Java Driver 3.1, you can use Projections:

collection.find().projection(Projections.include("name", "surname"));

Upvotes: 43

lobster1234
lobster1234

Reputation: 7779

You can pass another DBObject with the names of the fields and pass it here:

cur = coll.find(new BasicDBObject("id", 6655), your_dbobject_with_field_names);

Here is the API documentation

Upvotes: 12

Related Questions