Search code examples
javamongodbmongo-javamongo-collection

Using mongodb with java


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();
    }   
}

Solution

  • cursor.next() should be called only once, calling it second time will return next document. documentation

    NullPointerException could be thrown because next document does not exist or get("url") returns null.

    Following snippet should solve both issues.

        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();