public static ArrayList<DBObject> retrieve(String dbName, String collectionName, String key, String value)
{
ArrayList<DBObject> ar = new ArrayList();
MongoClient mongoClient = new MongoClient(new
MongoClientURI("mongodb://localhost:27017"));
@SuppressWarnings("deprecation")
DB database = mongoClient.getDB(dbName);
DBCollection collection = database.getCollection(collectionName);
BasicDBObject Query = new BasicDBObject();
Query.put(key, value);
DBCursor cursor = collection.find(Query);
while(cursor.hasNext()) {
LOGGER.info(cursor.next().toString());
ar.add(cursor.next());
}
LOGGER.info(ar.toString());
return(ar);
}
这是我的类函数,用于从数据库检索数据。我需要将此数据返回给另一个类。这是正确的方法吗?如果没有,我该怎么办?
数据示例:
[
{
"id": "234567",
"reportType": "Thyroid",
"age": 21,
"gender": "Female",
"onThyroxine": false,
"onAntiThyroideMed": false,
"sick": false,
"pregnant": false,
"recentThryoidSurgery": false,
"lithium": false,
"goitre": false,
"tumor": false,
"hypopituitary": false,
"i131Treatment": false,
"fti": 11,
"tbg": 123,
"tt4": 23,
"t3": 120,
"t4U": 12,
"tsh": 120
}
]
最佳答案
由于您需要返回查询结果中找到的所有文档,因此可以使用 DBCursor 的 toArray()
方法。
引用 - http://api.mongodb.com/java/current/com/mongodb/DBCursor.html
基本上是这样的 -
public static ArrayList<DBObject> retrieve(String dbName, String collectionName, String key, String value) {
MongoClient mongoClient = new MongoClient(new
MongoClientURI("mongodb://localhost:27017"));
@SuppressWarnings("deprecation")
DB database = mongoClient.getDB(dbName);
DBCollection collection = database.getCollection(collectionName);
BasicDBObject Query = new BasicDBObject();
Query.put(key, value);
return collection.find(Query).toArray();
}
关于java - 如何返回收到的mongodb数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48722103/