Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

mongodb

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

like image 202
kozher Avatar asked Jul 04 '11 08:07

kozher


2 Answers

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

collection.find().projection(Projections.include("name", "surname"));
like image 118
seb Avatar answered Sep 21 '22 19:09

seb


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);
like image 37
HungNM2 Avatar answered Sep 20 '22 19:09

HungNM2