2016-11-04 77 views
6

我想在Java中實現以下mongo查詢。如何使用Java驅動程序抑制mongodb中的列?

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}) 

我有以下的Java代碼,但我不知道如何添加抑制邏輯,

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

我需要添加{「_id」:0}中的代碼邏輯壓制「_id」字段。請讓我知道我該怎麼做到這一點。

回答

2

你可以嘗試這樣的事情。

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

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

排除其他領域

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

FindIterable<Document> resultSet = db.getCollection("document").find(query).projection(
fields(exclude("fieldname", "fieldvalue"))); 

對於預測的完整列表。

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

+0

它工作得很好...感謝偉大的信息共享! –