将mongodb与java结合使用
我正在数据库中搜索URL,但使用此代码我无法找到。为什么?通常我想打印数据库中存在的所有类型和URL。当我有打印只与类型是工作的,但与打印URL没有将mongodb与java结合使用,java,mongodb,mongo-java,mongo-collection,Java,Mongodb,Mongo Java,Mongo Collection,我正在数据库中搜索URL,但使用此代码我无法找到。为什么?通常我想打印数据库中存在的所有类型和URL。当我有打印只与类型是工作的,但与打印URL没有 MongoClient mongoClient; DB db; mongoClient = new MongoClient("localhost", 27017); db = mongoClient.getDB("behaviourDB_areas"); DBCollection cEvent = db.getCollection("
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();
}
}
cursor.next()
只应调用一次,第二次调用它将返回下一个文档
由于下一个文档不存在或get(“url”)
返回null
,因此可能引发NullPointerException
下面的代码片段应该可以解决这两个问题
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();
MongoClient-MongoClient=newmongoclient(“localhost”,27017);
MongoDatabase db=mongoClient.getDatabase(“行为数据库区域”);
MongoCollection cEvent=db.getCollection(“事件”,Document.class);
MongoCursorEvents=cEvent
.find(新的基本对象(“用户id”,“55b20db905f333defea9827f”))
.sort(新的BasicDBObject(“时间戳”,1))
.iterator();
整数计数=0;
if(cursorEvents.hasNext()){
Document doc=cursorEvents.next();
System.out.println(doc.getString(“type”);
如果(文件containsKey(“url”)){
System.out.println(doc.getString(“url”);
}
System.out.println(++计数);
}
cursorEvents.close();
mongoClient.close();
到底是什么不起作用?是否有任何错误消息?你期望发生什么?您使用哪种类型的收藏?数据到底是什么样子的?非常感谢您的回复…我对所有这些都很陌生…使用mongodb…使用java…我正在尝试!!只是基本的stackoverflow指南;)当我试着运行它时,我拍摄了这个(在第一张图片中)…并且它的数据必须像(在第二张图片中)。但是我只想拍摄类型,当出现url时,我也想要它。收集的类型是当某人在互联网上导航时发生的情况……并且必须在每个页面中找到每种类型的操作。(图片_1)(图片_2)您使用的是哪个版本的mongo驱动程序?