mongosh and JSON: normalized output
The CLI commands, like mongosh, can be used in bash scripts to quickly implement reliable data processing pipelines. Thanks to the aggregation pipeline your clients can do pretty complex things with this, despite a small number of lines and zero infrastructure. Unfortunately, in the recent versions, the output of those commands is no longer JSON. When mongosh returns results, it is now in pseudo-JSON, which can no longer be parsed directly by other standard tools like jq. This makes interpreting the results needlessly complicated. In addition, error messages are not output in JSON either (simple unformatted strings in that case), which adds another useless layer of complexity to handle the various errors.
My suggestion is that all the CLI tools, especially mongosh, should always output (or have at least an option to do so) its results, messages, and errors in a standard JSON format that can be readily consumed by other standard tools. Hopefully, you guys can find a way to expand the resulting JSON structures while retaining their backward compatibility as much as possible, instead of redefining the same fields' types over and over. This would make using those commands reliably inside scripts a breeze.
Note: I understand that the results might contain stuff like ObjectId() which are not JSON, but in that case, it is possible to rewrite them as { ..., ObjectId : "asdasd", ... } or { ..., ObjectIds : ["asda", "err34e", ...], ...}.
Starting with mongosh 1.6.0, it's now possible to pass a `--json` parameter to mongosh in conjunction with
`--eval`. For example:
$ mongosh $CONNECTION_STRING --eval 'db.coll.stats()' --json=relaxed --quiet | jq '{storageSize,totalSize}'
{
"storageSize": 36864,
"totalSize": 184320
}
If instead you are looking for a way to output JSON from a script, you can use `EJSON.stringify(thingToOutput, null, 2)`.