Gautam R
Gautam R

Reputation: 336

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": [
{"storeId":"1234"},
{"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.

Upvotes: 2

Views: 935

Answers (1)

s7vr
s7vr

Reputation: 75964

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")));

For complete list of projections.

http://api.mongodb.com/java/3.0/?com/mongodb/client/model/Projections.html http://mongodb.github.io/mongo-java-driver/3.0/builders/projections/

Upvotes: 3

Related Questions