【问题标题】:MongoDB - ReWriting Java 8 method in Java 7?MongoDB - 在 Java 7 中重写 Java 8 方法?
【发布时间】:2018-08-23 05:52:42
【问题描述】:

我有以下Java 方法可以搜索MongoDB 以查找特定条目:

  public List<Document> search(String collection, String entry){
        List<Document> documentList = new ArrayList<>();

        createIndexforCollection(collection);
        getCollection(collection).find(Filters.text(entry)).forEach((Block<? super Document>) documentList::add);

        return documentList;
    }

以上使用Java 8 功能,例如documentList::add ,但是在我正在进行的项目中,我只能使用 Java 7

我怎样才能重写上面有相同的逻辑using Java 7

【问题讨论】:

    标签: java mongodb java-8 mongodb-query java-7


    【解决方案1】:

    使用下面的代码。

    List<Document> documentList = new ArrayList<>();
    MongoCursor<Document> cursor = getCollection(collection).find(Filters.text(entry)).iterator();
    while(cursor.hasNext()) {
      Document document = cursor.next();
      documentList.add(document;  
    }
    

    【讨论】:

    • 抱歉错字。固定。
    【解决方案2】:

    试试这个。

     try(final DBCursor dbCursor = mongoTemplate.getCollection("YourCollectionName").find(Filters.text(entry))) {      
                while (dbCursor.hasNext()) {
                  Document document = dbCursor.next(); // You need to cast to the type you need
                  documentList.add(document);
                }
       }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-10-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-02
      • 2013-02-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多