【问题标题】:Using mongodb with java使用 mongodb 和 java
【发布时间】:2015-12-17 10:34:37
【问题描述】:

我正在数据库中搜索 URL,但使用此代码我不能。为什么?通常我想打印该数据库中存在的所有类型和 URL。当我只打印类型正常但打印的 URL 什么都没有时。

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

【问题讨论】:

  • 究竟是什么不工作?是否有任何错误信息?你期待发生什么?您使用什么类型的收藏?数据看起来如何?
  • 非常感谢您的回复.....我对这一切都很陌生......使用mongodb......使用java......我正在尝试!!
  • 只是基本的stackoverflow指南;)
  • 当我尝试运行它时..我拿这个(在第一张图片中)......以及它必须像的数据(在第二张图片中)。但我只想拿输入和何时出现 url 我也想要它。集合的类型是当有人在互联网上导航时发生的事情......并且必须在每个页面中找到每种类型的操作。 (图片_1)i.stack.imgur.com/KvNjr.jpg(图片_2)i.stack.imgur.com/eKybw.jpg
  • 您使用的是哪个版本的 mongo-driver?

标签: java mongodb mongo-java mongo-collection


【解决方案1】:

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

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

按照 sn-p 应该可以解决这两个问题。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-02-09
    • 2023-03-25
    • 1970-01-01
    • 2014-10-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多