java.lang.IllegalStateException:打开

时间:2015-02-11 06:23:23

标签: java mongodb

当我试图从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)

mycode的

    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。请建议我如何解决这个问题。

1 个答案:

答案 0 :(得分:4)

这就是您在致电mongo.close();之前致电cursor.hasNext())的原因。 从mongo.close();移除firstRecord并在循环后添加