Java: How to insert a hashmap into MongoDB?

2020-07-27 03:26发布

问题:

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

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]

Basically I want my MongoDB collecion to look like this:

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

Edit: 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.

Any help is appreciated.

回答1:

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

Something like

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