I need to communicate with MongoDB shell via Java
To explain in short, I am using something like Runtime.exec (commons exec specifically) to call MongoDB shell in –eval mode
Using this approach, I am able to successfully invoke MongoDB commands, retrieve the output into a stream (and print to stdout for example)
All is well till this point.
I need to now “parse” this output into something like an array of JSONObject
(I can make use of any JSON library like Jackson, etc. that may be appropriate for this)
so that I can “massage” the output based on some requirements. (Change the format, remove some key value pairs, etc.)
When I look at the output generated by printjson in case of arrays at least, it does not seem to be a valid json array but rather valid json objects separated by new line without the comma in between or enclosing [] that would make it a valid array.
In this case, any suggestions on how to parse this output into some kind of holder objects that I can use to read/modify key value pairs?
I don’t have the json commands at compile time but do know that these commands will always end in a printjson
EDIT –
So to simplify, for example, I am looking for a way to parse the following output into Java Objects –
(The individual key/value pairs are not known at compile time)
{
"_id" : ObjectId("4db0e0289523f82ff6cd90d4"),
"calendar_date" : "2009-11-10",
"product_id" : 8,
"channel" : "website",
"country" : "USA",
"total_unit_count" : 740,
"total_amount" : 11367.29
}
{
"_id" : ObjectId("4db0e0289523f82ff6cd90d5"),
"calendar_date" : "2009-11-10",
"product_id" : 8,
"channel" : "website",
"country" : "Australia",
"total_unit_count" : 740,
"total_amount" : 13893.09
}
{
"_id" : ObjectId("4db0e0289523f82ff6cd90d6"),
"calendar_date" : "2009-11-10",
"product_id" : 8,
"channel" : "retail",
"country" : "USA",
"total_unit_count" : 13,
"total_amount" : 8296.89
}
What I was looking for does not seem possible at the moment.
What I ended up doing was to shell out the mongo calls, obtain the result stream in java, JSONize the result (get rid of object_id since i dont need it, convert dates appropriately, etc.) and then generate a json object from this modified result string.
Ugly hack but the only one that seemed possible and it works.
If you ever find yourself in a similar boat and have specific questions, post in the comment below and I will help if I can.