2016-11-04 78 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

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