0

私はこの Web プロジェクトに取り組んでいます: Java、MongoDB、Freemarker Templates (FTL)

データはマップ内の 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;
        }

または、これは不可能であり、各値をマップに入れる結果をループする必要がありますか? このような:

        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;
        }           

助けと提案をありがとう!

4

1 に答える 1

0

多分これはあなたが必要とするものです:

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;
} 
于 2012-10-26T22:28:07.943 に答える