whereswalden whereswalden - 1 month ago 25
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

NumberLong
,
Date
, and
Timestamp
. 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
db.serverStatus()
in things that do output strict JSON, like
mongodump
. 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

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:

JSON.stringify(db.serverStatus())

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.