Paul
Paul

Reputation: 209

Convert MongoDB Document to Extended JSON in Shell

I am looking for a Shell tool that can convert a mongodb document into extended JSON.

So if the original JSON file looks like this:

{
    "_id" : ObjectId("5a8c60b8c83eaf000fb39547"),
    "name" : "myName",
    "created" : ISODate("2018-02-20T17:54:00.091Z"),
    "components" : [
        ...

The result would be something like this:

{
    "$oid" : "5a8c60b8c83eaf000fb39547",
    "name" : "myName",
    "created" : { "$date" : "2018-02-20T17:54:00.091Z"},
    "components" : [
        ...

Upvotes: 3

Views: 1283

Answers (1)

Harsh Shah
Harsh Shah

Reputation: 1596

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.

Upvotes: 1

Related Questions