Search code examples
mongodbmongodb-java

MongoDB Java driver aggregate String


I am getting a String with the structure of JSONArray [ { "abc" : "123" }, { "def" : "456" } ]which I need to use to call mongoCollection.aggregate(theString);

The aggregate function takes List<? extends Bson> and I am not sure what is the best way to convert the String to List<? extends Bson>.

For find() method which takes Bson var1 I am just converting the String to Document using Document.parse(theString);

I am using mongodb 3.4.


Solution

  • I was able to come up with this but it looks a little ugly.

            JSONArray array = new JSONArray(theString);
            List<Document> list = new ArrayList<>();
            for(Object jsonObject : jsonArray){
                Document document = Document.parse(jsonObject.toString());
                list.add(document);
            }
            collection.aggregate(list);