MongoDB upgraded their command-line interface (formerly mongo, now mongosh). Before, the mongo command output was in proper JSON, the kind jq could ingest.
For example:
{ "abc" : "hello" }
The new mongosh command now outputs stuff like:
{ abc: 'hello' }
…which can’t be parsed by jq.
Is there a way to standardize mongosh to output standard JSON?
If not, is there any shell command that filters "incorrect but coherent" JSON (from stdin) and normalizes it into a standard form (to stdout)?
3
Answers
A MongoDB employee recommends using the
EJSON.stringify
wrapper, e.g.:Except for extensions such as
Long(_)
andDate(_)
, it looks likehjson
could also be used.In principle you can use
JSON.stringify()
. However it has some limitations, see this example:Date
objects are converted into strings.An alternative could be
EJSON.stringify()
, which recognizes data types likeDate
. It is also mentioned in documentation:However, the values are printed as
{"$date": "2022-03-26T11:15:53.750Z"}
My solution is a customized function.
tojson
andtojsononeline
do not exist anymore inmongosh
, so I created my own:There are a few more data types used in MongoDB, however I think they are hardly relevant. Otherwise add a few more
replace()
operations.Anther solution is to install "mongosh snippet", either with
snippet install mongocompat
, or download scripts from https://github.com/mongodb-labs/mongosh-snippets/tree/main/snippets/mongocompat and runPreferable put these 3 lines in your
.mongoshrc.js
file.These 3 scripts define (almost?) all function from legacy
mongo
shell which are not (yet) available in newmongosh
Be aware, when you move to new
mongosh
, then your application may face some more differences, see for example mongosh Data TypesYou can wrap your queries inside
EJSON.stringify
from insidemongosh
console.Eg: if you want to run the query
db.books.find({"book-id":"123456789"})
execute the following.