Question

I would like to get some information which is in a mongoDB except some attributes.

I tried it in cmd and it worked:

db.orders.find({name:"chabeee"},{_id:0, name:1, worksAt:1})

Then I get this result:

{ "name" : "chabeee", "worksAt" : "jobAtBp" }
{ "name" : "chabeee", "worksAt" : "jobAtRE" }

Its okay, but I want to get in a Java Program. How can I do that?

Was it helpful?

Solution

You have to create one additional BasicDBObject, which will be used for pointing out which exact keys to be fetched. And finally the DBCollection#find(DBObject ref, DBObject keys) method has to be invoked in order to pass the desired projection keys.

BasicDBObject query = new BasicDBObject("name", "chabeee");
BasicDBObject keys = new BasicDBObject();
keys.put("_id", 0);
keys.put("name", 1);
keys.put("worksAt", 1);
BasicDBCursor result = collection.find(query, keys);

Then you just have to iterate over the BasicDBCursor and verify the result.

while (cursor.hasNext()) {
    System.out.println(cursor.next());
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top