0

I'm searching in the database for the URL but with this code I can not. Why? Normally I want to print all the type and the URL where exist in this database. When I have the print only with the type is working but with the print for URL nothing.

MongoClient mongoClient;
DB db;

mongoClient = new MongoClient("localhost", 27017);
db = mongoClient.getDB("behaviourDB_areas");    


DBCollection cEvent = db.getCollection("event");

    BasicDBObject orderBy = new BasicDBObject();
    orderBy.put("timeStamp",1);


    DBCursor cursorEvents = null;

    BasicDBObject searchQuery = new BasicDBObject();
    searchQuery.put("user_id", "55b20db905f333defea9827f");

    cursorEvents = cEvent.find(searchQuery).sort(orderBy);

        int count=0;

        if(cursorEvents.hasNext()){

            while(cursorEvents.hasNext()){

                count++;           

                System.out.println(cursorEvents.next().get("type").toString());
                System.out.println(cursorEvents.next().get("url").toString());
                System.out.println(count);
            }   
        }

        mongoClient.close();
    }   
}
4

1 回答 1

0

cursor.next()应该只调用一次,第二次调用将返回下一个文档。文件

NullPointerException可能会因为下一个文档不存在或get("url")返回而被抛出null

以下代码段应该可以解决这两个问题。

    MongoClient mongoClient = new MongoClient("localhost", 27017);
    MongoDatabase db = mongoClient.getDatabase("behaviourDB_areas");
    MongoCollection cEvent = db.getCollection("event", Document.class);

    MongoCursor<Document> cursorEvents = cEvent
            .find(new BasicDBObject("user_id", "55b20db905f333defea9827f"))
            .sort(new BasicDBObject("timeStamp",1))
            .iterator();

    int count = 0;

    if(cursorEvents.hasNext()) {
        Document doc = cursorEvents.next();
        System.out.println(doc.getString("type"));
        if (doc.containsKey("url")) {
            System.out.println(doc.getString("url"));
        }
        System.out.println(++count);
    }

    cursorEvents.close();
    mongoClient.close();
于 2015-12-17T10:52:26.977 回答