whereswalden whereswalden - 9 months ago 89
JSON Question

Force mongodb to output strict JSON

I want to consume the raw output of some MongoDB commands in other programs that speak JSON. When I run commands in the mongo shell, they represent Extended JSON, fields in "shell mode", with special fields like

, and
. I see references in the documentation to "strict mode", but I see no way to turn it on for the shell, or a way to run commands like
in things that do output strict JSON, like
. How can I force Mongo to output output standards-compliant JSON?

There are several other questions on this topic, but I don't find any of their answers particularly satisfactory.

Answer Source

The MongoDB shell speaks Javascript, so the answer is simple: use JSON.stringify(). If your command is db.serverStatus(), then you can simply do this:


This won't output the proper "strict mode" representation of each of the fields ({ "floatApprox": <number> } instead of { "$numberLong": "<number>" }), but if what you care about is getting standards-compliant JSON out, this'll do the trick.