当我试图从 Mongodb 读取数据时,我收到了这个异常,

java.lang.IllegalStateException: open
    at org.bson.util.Assertions.isTrue(Assertions.java:36)
    at com.mongodb.DBTCPConnector.isMongosConnection(DBTCPConnector.java:369)
    at com.mongodb.Mongo.isMongosConnection(Mongo.java:645)
    at com.mongodb.DBCursor._check(DBCursor.java:454)
    at com.mongodb.DBCursor._hasNext(DBCursor.java:546)
    at com.mongodb.DBCursor.hasNext(DBCursor.java:571)
    at com.calsoftlabs.mongo.client.impl.ReadingData.main(ReadingData.java:93)

我的代码
    public static DBCursor firstRecord(String ip) throws Exception {

        DBObject query = new BasicDBObject("client_ip", ip);

        DBCollection collection = getConnection();

        DBObject obj = new BasicDBObject("_id", 1);

        DBCursor cursor = collection.find(query).sort(obj).limit(1);

        mongo.close();

        return cursor;

    }
    DBCursor cursor = ReadingData.firstRecord(ip);

                    while (cursor.hasNext()) {

                        cursor.next();

                        myList.add(new BasicDBObject("client_ip", (String) cursor.curr().get(
                                "client_ip")).append("timestamp",
                                (String) cursor.curr().get("timestamp")).append("total_traffic",
                                (String) cursor.curr().get("total_traffic")));

                    }

通过使用上面的代码,我正在从 Mongodb 的记录集中读取第一条记录,但是 cursor.hasNext() 行抛出了 IllegalStateException。请建议我如何解决这个问题..

最佳答案

这就是您在调用 mongo.close(); 之前调用 cursor.hasNext()) 的原因。
mongo.close(); 中删除 firstRecord 并将其添加到循环之后

关于java.lang.IllegalStateException : open,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/28447801/

10-12 05:03