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
}
]
答案 0 :(得分:0)
由于您需要返回查询结果中找到的所有文档,因此可以使用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();
}
答案 1 :(得分:0)
您可以在需要引用此数据的另一个类中创建此类的对象。
您可以在需要此数据的类中调用此类对象的.retrieve()
方法。
答案 2 :(得分:0)
编辑代码:
public static List<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);
List<DBObject> obj = collection.find(Query).limit(100).toArray();
LOGGER.info(obj.toString());
return(obj);
}
参考瑞诗凯诗的回答,这是更新后的代码。这非常有效。