Querying Mongo Collection using QueryBuilder in Mongo 3.3.0

吃可爱长大的小学妹 提交于 2019-12-25 04:50:07

问题


Our code with mongo-java-driver 3.0.4 used to be like -

DBCollection dbCollection = mongoClient.getDB(databaseName).getCollection(collectionName);
QueryBuilder queryBuilder = new QueryBuilder();
/** queryBuilder.put() for building the query */
DBCursor dbCursor = dbCollection.find(queryBuilder.get());
while(dbCursor.hasNext()) {
    DBObject dbObject = dbCursor.next();
    // add entries to a list of TDocument type
}

Converting this to the mongo-java-driver 3.3.0, I ended up with this -

MongoCollection<TDocument> collection = database.getCollection(collectionName, TDocument.class); //where TDocument is custom document class of ours
QueryBuilder queryBuilder = new QueryBuilder();
/** queryBuilder.put() for building the query */
FindIterable<TDocument> tDocumentList = collection.find(queryBuilder.get()); //this is not compiling
for (TDocument element : tDocumentList) {
    names.add(element.getName()); //addition to some list of TDocument type
}

But the point is I am still not able to compile the source for the find operation on the MongoDB collection that I have defined.

What needs to be corrected here? I would want to stick to any preferred implementation that helps in upgrading mongo to 3.3.0+.

Edit - My TDocument class (named differently below from the lib name) class is a simple POJO as -

public class TDocType {

    private TDocType() {
    }

    String one;

    @NotNull
    String name;

    String third;

    String fourth;

    // getter and setter for all the above
}

回答1:


Cast to Bson.

 FindIterable<TDocument> tDocumentList = collection.find((Bson)queryBuilder.get()); 

Update:: Change to use the filters from Mongo 3.3.0

Bson filter = Filters.eq("field", "value");
FindIterable<TDocument> tDocumentList = collection.find(filter);



回答2:


You could replace your query builder by a org.bson.Document like this :

Document query = new Document();
query.put(parameterName, parameterValue);

And then

FindIterable<TDocument> tDocumentList = collection.find(query); //this is not compiling


来源:https://stackoverflow.com/questions/40178038/querying-mongo-collection-using-querybuilder-in-mongo-3-3-0

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!