在上面的MongoDB 3.3.0中使用QueryBuilder和BasicDBObjectBuilder

时间:2016-10-21 15:02:23

标签: java mongodb mongodb-query mongodb-java

第1部分

跟进Querying Mongo Collection using QueryBuilder in Mongo 3.3.0的解决方案 ,我尝试实现建议的方法来实现collection.find()。但是被卡在不同参数上的BasicDBObjectBuilder传递给了以下相同的内容 -

BasicDBObjectBuilder queryBuilder = BasicDBObjectBuilder.start();

query.getParams().entrySet().stream().forEach(entry -> queryBuilder.add(entry.getKey(), entry.getValue()));


BasicDBObjectBuilder outputQuery = BasicDBObjectBuilder.start();
outputQuery.add(nameKey, 1);

这不会编译:

FindIterable<TDocType> tDocTypeList = collection.find(queryBuilder.get(), outputQuery.get());

这也不会编译:

FindIterable<TDocType> tDocTypeList = collection.find((Bson)queryBuilder.get(), (Bson)outputQuery.get()); 

这不会编译:

org.bson.Document queryBuilder = new org.bson.Document();

query.getParams().entrySet().stream().forEach(entry -> queryBuilder.put(entry.getKey(), entry.getValue()));

org.bson.Document outputQuery = new org.bson.Document();
outputQuery.put(nameKey, 1); 

FindIterable<TDocType> tDocTypeList = collection.find(queryBuilder, outputQuery); 
  

问题 - 如何为集合中projection所需的结果指定find()

第2部分

一方面我可以简单地替换mongo 3.0.4 java驱动程序的代码 -

DBObject dbObject = collection.findOne(new QueryBuilder().put(ids).is(id).get())

Bson filter = Filters.eq(ids, id);
TDocType doc = collection.find(filter).first();

现在,如果我们有一个实现,我们通过迭代构建查询,如示例代码 -

for(Map.Entry<String, Object> entry : query.getParams().entrySet()) {
    // this is where its building the query
    if(some condition) {
        queryBuilder.put(entry.getKey()).is(entry.getValue()); 
    }
    if(some other condition) {
        queryBuilder.put(entry.getKey()).in(query.getValues());
    }
}
  

问题 - 有没有办法实现这样的追加查询过滤器   目前mongo 3.3.0+也是如此?

1 个答案:

答案 0 :(得分:2)

find方法的第二个参数是结果类型。请尝试以下方式。

FindIterable<TDocType> tDocTypeList = dbCollection.find(filter, TDocType.class);

投影更新

FindIterable<TDocType> tDocTypeList = dbCollection.find(filter, TDocType.class).projection(outputQuery);

附加过滤器的更新

List<Bson> filters = new ArrayList<>();
for (Map.Entry<String, Object> entry : query.getParams().entrySet()) {
        // this is where its building the query
   if (some condition){
       filters.add(Filters.eq(entry.getKey(), entry.getValue()));
   }
   if (some other condition){
       filters.add(Filters.in(entry.getKey(), query.getValues()));
   }
}
FindIterable<TDocType> docType = dbCollection.find(Filters.and(filters));