如何使用 Java 从 MongoDB 版本 3.4 获取数据?
How to get data from MongoDB version 3.4 using Java?
我正在尝试从 java 中的 mongodb 收集数据,我需要使用 select 查询并将其放入 jtextarea。 Select 查询将填充组合框元素。
代码如下:
/**** 连接到 MongoDB ****/
MongoClientURI connectionString = new MongoClientURI("mongodb://localhost:27017");
MongoClient mClient = new MongoClient(connectionString);
/**** Get database ****/
MongoDatabase db = mClient.getDatabase("productDB");
mClient.getAddress();
/**** Get collection / table from 'productDB' ****/
MongoCollection<Document> tableCollection = db.getCollection("local");
/**** Find and display ****/
Document whereQuery = new Document();
whereQuery.put("Product Category",categoryCB.getSelectedIndex());
MongoCursor<Document> cursor = tableCollection.find(whereQuery);
mClient.close();
在tableCollection.find中显示:
cannot convert from FindIterable to MongoCursor
有什么不同的方法吗?
您正在尝试在 MongoCursor 引用中接收 FindIterable 对象。
将引用变量'cursor'的类型从MongoCursor更改为FindIterable或其超类型 MongoIterable.
FindIterable<Document> cursor = tableCollection.find(whereQuery);
(或)
MongoIterable<Document> cursor = tableCollection.find(whereQuery);
我已经找到解决这个问题的代码并且它有效,主要部分在下面的代码中
mClient = new MongoClient(connectionString);
db = mClient.getDatabase("Your Database Name");
tableCollection = db.getCollection("Your Table Name");
whereQuery = new Document();
whereQuery.put("Your Attribute", typeCB.getSelectedItem().toString());
iterator=tableCollection.find(whereQuery);
cursor = iterator.iterator();
while (cursor.hasNext())
{
/*put your code here*/
}
我正在尝试从 java 中的 mongodb 收集数据,我需要使用 select 查询并将其放入 jtextarea。 Select 查询将填充组合框元素。
代码如下:
/**** 连接到 MongoDB ****/
MongoClientURI connectionString = new MongoClientURI("mongodb://localhost:27017");
MongoClient mClient = new MongoClient(connectionString);
/**** Get database ****/
MongoDatabase db = mClient.getDatabase("productDB");
mClient.getAddress();
/**** Get collection / table from 'productDB' ****/
MongoCollection<Document> tableCollection = db.getCollection("local");
/**** Find and display ****/
Document whereQuery = new Document();
whereQuery.put("Product Category",categoryCB.getSelectedIndex());
MongoCursor<Document> cursor = tableCollection.find(whereQuery);
mClient.close();
在tableCollection.find中显示:
cannot convert from FindIterable to MongoCursor
有什么不同的方法吗?
您正在尝试在 MongoCursor 引用中接收 FindIterable 对象。
将引用变量'cursor'的类型从MongoCursor更改为FindIterable或其超类型 MongoIterable.
FindIterable<Document> cursor = tableCollection.find(whereQuery);
(或)
MongoIterable<Document> cursor = tableCollection.find(whereQuery);
我已经找到解决这个问题的代码并且它有效,主要部分在下面的代码中
mClient = new MongoClient(connectionString);
db = mClient.getDatabase("Your Database Name");
tableCollection = db.getCollection("Your Table Name");
whereQuery = new Document();
whereQuery.put("Your Attribute", typeCB.getSelectedItem().toString());
iterator=tableCollection.find(whereQuery);
cursor = iterator.iterator();
while (cursor.hasNext())
{
/*put your code here*/
}