繁体   English   中英

如何使用Java在mongoDB中保存和读取地图

[英]how to save and read map in mongoDB using java

我在mongo中有一个包含3列的集合,如下所示:

{ 
"_id" : { "$oid" : "5396ad5de4b09ea27a641ed6"} , 
"word" : "test_word" , 
"doc_occurrence" : "'total':25,'sport':10" ,
 "total_occurrence" : "'total':32,'sport':15"
}

doc_occurrence和total_occurrence是Map。 我以这种方式插入文档以进行收集:

        private boolean add(String word, Map<String, Integer> docOccurrence, Map<String, Integer> totalOccurrence) {
    BasicDBObject document = new BasicDBObject();
    document.put("word", word);
    document.put("docOccurrence", docOccurrence);
    document.put("totalOccurrence", totalOccurrence);
    try {
        synchronized (LOCK_WRITE) {
            table.insert(WriteConcern.SAFE,document);


        }
    } catch (MongoException e) {
        logger.error("Could not insert new row to word_cat : {}", e.getMessage());
        return false;
    }
    return true;
}

我想以这种方式从数据库读取地图:

        BasicDBObject searchQuery = new BasicDBObject();
        searchQuery.put("word",word);
    try {
        DBCursor cursor = table.find(searchQuery);
        if (cursor.hasNext()) {
            DBObject doc = cursor.next();
            Map<String, Integer> map = (Map<String, Integer>)doc.get("docOccurrence"); // ClassCastException

但我明白了

java.lang.ClassCastException: java.lang.String cannot be cast to java.util.Map

我可以直接从数据库中读取地图吗? 如果没有,什么是替代品?

ps:BSON将映射转换为String。 实际上,BSON密钥必须是String!

这里的问题是创建的BSON对象的Map部分放置在构造函数的“字符串”大小中,因此在此调用中存在一个隐式的“ stringify”。

作为BSON Object构造函数的唯一参数包装,然后Map正确序列化:

document.put("word", word);
document.put("docOccurrence", new BasicDBObject(docOccurrence));
document.put("totalOccurrence", new BasicDBObject(totalOccurrence));

BasicDBObject类实现AbstractMap接口,并且应该能够以这种方式在读取的数据上使用。 其余代码应按预期工作。

我建议您阅读有关MongoDB和NoSQL的更多信息,因为您似乎对整个概念感到困惑。

您在mongodb中有一个集合 ,该集合文档包含3个字段 ,但_id除外。 您的doc_occurrencetotal_occurrence字段的值应为** subdocument ** s(另一个json对象),这就是MongoDB滚动的方式。 您使用字符串csv值而不是子文档是完全无效和错误的。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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