Java:如何将哈希图插入MongoDB? [英] Java: How to insert a hashmap into MongoDB?

查看:52
本文介绍了Java:如何将哈希图插入MongoDB?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个哈希表,试图将其插入到MongoDB(版本3.6)中.我知道方法insertMany()-仅使用文档列表.我无法创建列表,因为我的数据中有重复项,并且希望摆脱它们.这就是为什么我要创建一个哈希图.有什么办法可以将哈希图插入到Mongodb中吗?我找到了一个链接 https://www.mkyong.com/mongodb /java-mongodb-insert-a-document/展示了如何将地图插入Mongodb

I have a hashmap which I am trying to insert into MongoDB(version 3.6). I know about the method insertMany() -- which takes only List of Documents. I cannot create a list because I have duplicates in my data and I want to get rid of them. That's why I am creating a hashmap. Is there any way I can to insert the hashmap into Mongodb? I found one link https://www.mkyong.com/mongodb/java-mongodb-insert-a-document/ which shows how to insert the map into Mongodb

collection.insert(new BasicDBObject(documentMap));

但是在新的mongoDB中不推荐使用BasicDBObject.我的哈希图看起来像这样:

But BasicDBObject is deprecated in the new mongoDB. My hashmap looks like this:

-1322771423 [ecn, KeywordMatch, http://insidedell.com/ecn, ECN]
-2144339676 [product marketing, PhraseMatch, http://dellemc.com/product, Products]
-214203024 [jive, ExactMatch, http://test.com/jive, Jive test]
-493382214 [search, ExactMatch, http://example.com, Search Consultancy]

基本上我希望我的MongoDB集合看起来像这样:

Basically I want my MongoDB collecion to look like this:

new_collection
{
_id: -493382214
query: ExactMatch,
link: http://example.com,
content: Search Consultancy
}
{
_id:
...
}

我的问题背景:我正在尝试将CS​​V文件插入MongoDB.我的CSV文件有重复行(相同的行).这就是为什么我必须将它们转换为哈希图,而不是将它们存储在arrayList(Document)中.我知道我们可以使用insertMany(List(Document))插入Mongodb,但是我需要避免重复.

Background on my problem: I am trying to insert a CSV file into MongoDB. My CSV file has duplicates row(identical row). That's why I have to convert them into a hashmap instead of storing them in an arrayList(Document). I know we can insert into Mongodb by using insertMany(List(Document)), but I need to avoid those duplicates.

感谢您的帮助.

推荐答案

使用for循环映射_id和值并将所有值收集到文档列表中.

Use for loop to map the _id and values and collect all values into list of documents.

类似

Map<String, List<String>> inMap =  new HashMap<>();
  List<Document> documents = new ArrayList<>();
  for(Map.Entry<String, List<String>> kv :inMap.entrySet()) {
     Document doc = new Document();
     doc.put("_id", kv.getKey());
     List<String> values = kv.getValue();
     doc.put("query", values.get(0));
            ... rest of values
     documents.add(doc);
  }
collection.insertMany(documents);

这篇关于Java:如何将哈希图插入MongoDB?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆