Gautam R Gautam R - 1 year ago 82
Java Question

How to suppress a column in mongodb using Java drivers?

I would like to achieve the following mongo query in Java.

db.getCollection('document').find({ "$and": [
{"tranDate" : {"$gte":new Date("Sat,01 Oct 2016 00:00:00 GMT"),
"$lte":new Date("Mon,31 Oct 2016 00:00:00 GMT")}}
{"_id" : 0})

I have the following java code, but I'm not sure how to add the suppress logic,

List<Bson> conditions = new ArrayList<>();
conditions.add(eq("field1", "value1"));
conditions.add(eq("field2", "value2"));
Bson query = and(conditions);
FindIterable<Document> resultSet = db.getCollection("document").find(query);

I need to add {"_id" : 0} in the code logic to suppress "_id" field. Kindly let me know how can I achieve this.

Answer Source

You can try something like this.

import static com.mongodb.client.model.Projections.excludeId;

FindIterable<Document> resultSet = db.getCollection("document").find(query).projection(excludeId());

Exclude Other Fields

import static com.mongodb.client.model.Projections.fields;

FindIterable<Document> resultSet = db.getCollection("document").find(query).projection(
fields(exclude("fieldname", "fieldvalue")));
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download