【问题标题】:Querying Mongo Collection using QueryBuilder in Mongo 3.3.0在 Mongo 3.3.0 中使用 QueryBuilder 查询 Mongo 集合
【发布时间】:2016-10-21 13:32:58
【问题描述】:

我们使用 mongo-java-driver 3.0.4 的代码曾经是这样的 -

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
}

将其转换为 mongo-java-driver 3.3.0,我最终得到了这个 -

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
}

但关键是我仍然无法为我定义的 MongoDB 集合上的find 操作编译源代码。

这里需要纠正什么?我想坚持任何有助于将 mongo 升级到 3.3.0+ 的首选实现。

编辑 - 我的 TDocument 类(下面的命名与 lib 名称不同)类是一个简单的 POJO,因为 -

public class TDocType {

    private TDocType() {
    }

    String one;

    @NotNull
    String name;

    String third;

    String fourth;

    // getter and setter for all the above
}

【问题讨论】:

  • 您的 TDocument 看起来如何?这会扩展 DBObject 吗?将该课程添加到帖子中。
  • @Veeram 添加,不知道为什么需要它。
  • 您可以将其转换为 collection.find((Bson)queryBuilder.get())
  • Veeram Vincent 你也可以看看这个 (stackoverflow.com/questions/40179940) 吗?将根据可以遵循的一致方法标记对此的解决方案。

标签: java mongodb mongodb-query mongodb-java


【解决方案1】:

转换为 Bson。

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

更新:: 更改为使用 Mongo 3.3.0 中的过滤器

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

【讨论】:

  • 你也可以看看这个(stackoverflow.com/questions/40179940)吗?将根据可以遵循的一致方法标记解决方案
【解决方案2】:

您可以像这样用 org.bson.Document 替换您的查询生成器:

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

然后

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

【讨论】:

  • 纠正最后一行代码 -> query.get() 也不起作用,需要 Object 类型的 key
  • 我的错,它只是查询而不是 query.get()
  • 你也可以看看这个(stackoverflow.com/questions/40179940)吗?将根据可以遵循的一致方法标记解决方案
猜你喜欢
  • 1970-01-01
  • 2021-12-30
  • 1970-01-01
  • 2019-10-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-05-02
相关资源
最近更新 更多