我是 MongoDB 的初学者,我正在使用 JAVA 驱动程序来使用它。
我有以下代码
MongoClient client = new MongoClient();
DB d = client.getDB("world");
DBCollection c = d.getCollection("zips");
DBCursor cursor = c.find();
现在我的问题是我想使用一个简单的光标来浏览文档。 getDB() 方法已被弃用,但它工作正常。在文档中提到 getDB 可以替换为 MongoClient.getDatabase();但 getDatabase() 返回 MongoDatabase 而不是 DB。
有人可以指出在不使用任何已弃用的方法的情况下制作 DBCursor 的正确方法吗?谢谢。
PS:我知道有像 morphia、jongo 等框架,但请不要让它们参与讨论。我目前只想求助于 JAVA 驱动程序。
编辑:区别在于在 JAVA 驱动程序中获取游标,而不是在 DB 和 MongoClient 之间获取游标
是的。这是真的。您可以将 getDB 替换为 getDatabase。这就是你可以如何使用它。
/**** Get database ****/
// if database doesn't exists, MongoDB will create it for you
MongoDatabase mydatabase = mongoClient.getDatabase("mydatabase");
/**** Get collection / table from 'testdb' ****/
// if collection doesn't exists, MongoDB will create it for you
FindIterable<Document> mydatabaserecords = mydatabase.getCollection("collectionName").find();
MongoCursor<Document> iterator = mydatabaserecords.iterator();
while (iterator.hasNext()) {
Document doc = iterator.next();
// do something with document
}
Example:
假设您的文档如下所示:
{
"name": "Newton",
"age": 25
}
然后可以如下获取字段
while (iterator.hasNext()) {
Document doc = iterator.next();
String name = doc.getString("name");
int age = doc.getInteger("age");
System.out.println("Name: " + name);
System.out.println("Age: " + age);
}
我希望这能消除您的疑虑。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)