简体   繁体   English

MongoDB,Java和Freemarker模板(FLT)

[英]MongoDB, Java and Freemarker Templates (FLT)

I'm working on this web project with: Java, MongoDB and Freemarker Templates (FTL) 我正在使用以下Web项目进行操作:Java,MongoDB和Freemarker模板(FTL)

The data is sent to the FTL pages within a Map. 数据被发送到Map中的FTL页面。

Now I would like to know if it's possible to convert the result from a Mongo query straight into a Map and then send this to the FTL template. 现在,我想知道是否有可能将Mongo查询的结果直接转换为Map,然后将其发送到FTL模板。

For example: I would like to query all the members from a collection and put this in Map to use in the FTL template. 例如:我想查询集合中的所有成员,并将其放入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;
        }

Or is this not possible and I would need to loop over the results putting each value into a Map? 还是这不可能,我需要遍历将每个值放入Map中的结果? Like this: 像这样:

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

Thanks for any help and suggestions! 感谢您的帮助和建议!

maybe this is what you need: 也许这就是您所需要的:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM