-->

QueryBuilder and BasicDBObjectBuilder usage in Mon

2020-05-06 11:50发布

问题:

PART 1

Following up solutions to Querying Mongo Collection using QueryBuilder in Mongo 3.3.0 , I tried implementing the suggested methods to implement collection.find(). But was stuck with different parameters been passed a BasicDBObjectBuilder to the same as follows -

BasicDBObjectBuilder queryBuilder = BasicDBObjectBuilder.start();

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


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

This doesn't compile :

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

This also won't compile :

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

And this won't compile either :

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

Question - How do I specify a projection for the results required out of find() from collections?


PART 2

At one end I can simply replace mongo 3.0.4 java driver's code -

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

to

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

Now if we have an implementation where we build query through an iteration as in the sample code -

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

Question - Is there a way to implement such appending query Filters with current mongo 3.3.0+ as well?

回答1:

The second argument of find method is result type. Try as below.

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

Update for projection

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

Update for appending filters

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