[英]MongoDB, Java and Freemarker Templates (FLT)
我正在使用以下Web項目進行操作:Java,MongoDB和Freemarker模板(FTL)
數據被發送到Map中的FTL頁面。
現在,我想知道是否有可能將Mongo查詢的結果直接轉換為Map,然后將其發送到FTL模板。
例如:我想查詢集合中的所有成員,並將其放入Map中以在FTL模板中使用。
public Map<String, Object> getAllMembers() {
DBCollection collection =database.getCollection("members");
BasicDBObject query = new BasicDBObject();
DBCursor cur = collection.find(query);
DBObject one = cur.next();
HashMap<String,Object> result = one;
return result;
}
還是這不可能,我需要遍歷將每個值放入Map中的結果? 像這樣:
public Map<String, Object> getAllMembers(f){
DBCollection collection = database.getCollection("members");
DBCursor cursor = collection.find();
Map<String,Object> itemMap = new HashMap<String, Object>();
DBObject one;
while(cursor.hasNext()) {
one = cursor.next();
itemMap.put((String)one.get("id"),one.get("name"));
}
return itemMap;
}
感謝您的幫助和建議!
也許這就是您所需要的:
public Map<String, Object> fetch(DB db, String collName, String key, String value){
Map<String,Object> result = new HashMap<String, Object>();
DBCollection coll = db.getCollection(collName);
BasicDBObject query = new BasicDBObject();
query.put(key, value);
DBCursor cur = coll.find(query);
while(cur.hasNext()) {
result.putAll(cur.next().toMap());
}
return result;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.