2016-12-30 70 views
1

我们试图从数据库(MongoDB)中检索条目并将它们放入数据库中。当使用DBCursor时,我们使用cursor.hasNext()来获取下一个阅读。如何遍历MongoDB 3.0中的条目?

DBCursor在MongoDB 2.0中折旧,建议使用FindIterable for MongoDB 3.0。

但是,当我们使用FindIterable时,没有类似的hasNext()方法。

如何将我的代码更改为3.0以下?

BasicDBObject query = new BasicDBObject("timeStamp", 
         new BasicDBObject("$gte",from).append("$lt",to)); 
    DBCursor cursor = (DBCursor) newColl.find(query); 
    //FindIterable cursor = newColl.find(query); 
    while (cursor.hasNext()) { 
      DBObject latestEntry = cursor.next(); 
      String json = latestEntry.toString(); 
      Reading reading = gson.fromJson(json, Reading.class); 
      readingList.add(reading); 

    } 
    return readingList; 

回答

2

你可以尝试下面的东西。

Document query = new Document("timeStamp", 
         new Document("$gte",from).append("$lt",to)); 
FindIterable<Document> find = newColl.find(query); 
for (Document latestEntry : find) { 
     String json = latestEntry.toJson(); 
     Reading reading = gson.fromJson(json, Reading.class); 
     readingList.add(reading); 
} 
return readingList; 

使用游标

MongoCursor<Document> cursor = newColl.find(query).iterator(); 
while (cursor.hasNext()) { 
     Document latestEntry = cursor.next(); 
     String json = latestEntry.toJson(); 
     Reading reading = gson.fromJson(json, Reading.class); 
     readingList.add(reading); 
} 
return readingList; 

使用lambda

List<Reading> readingList= newColl.find().map(item -> gson.fromJson(item.toJson(), Reading.class)).into(new ArrayList<>());