Reputation: 725
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
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
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
Reputation: 818
If you are using Java Driver 3.1, you can use Projections:
collection.find().projection(Projections.include("name", "surname"));
Upvotes: 43
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