EJSON output from mongosh

The following previous answer partially solved what I wanted to achieve.

I’m pulling data out of a mongo instance running in a kubernettes cluster (and can’t connect using a GUI like Compass). Compass has a view of the data that converts the document to JSON. Using EJSON.stringify and the toArray() method almost gives the output I was hoping for. I’m totally new to mongo and have some follow up questions.

  1. Is there a way to output the EJSON.stringify format on queries once already running the mongosh? For my purposes the “pretty” output isn’t really useful as I (ideally) want to be able to copy and paste output.

  2. The output of the eval is mostly great but I’ve noticed that certain fields lose their data type descriptors. For example in my database we have some integers defined as Long. The current output of the EJSON.stringify for these fields is { "myLong": 12345 } whereas I was hoping for something more like "myLong": { "$numberLong": "12345" } which more closely matches the Compass output. Is there a way to retain this detail? The saved output will form part of a test that will inject this data back into an empty db so I’d like it as close to reality as possible.

Thanks in advance, happy to be pointed to docs I may have missed. Still learning.

Is there a way to output the EJSON.stringify format on queries once already running the mongosh? For

You can use EJSON.stringify() in the regular mongosh prompt as well on the result of .toArray(), e.g. EJSON.stringify(db.test.find().toArray(), null, 2) is totally fine.

but I’ve noticed that certain fields lose their data type descriptors

You might be looking for relaxed: false:

test> EJSON.stringify(db.longtest.find().toArray(), null, 2, { relaxed: false })
[
  {
    "_id": {
      "$oid": "60ca0404216deba577090bc4"
    },
    "l": {
      "$numberLong": "1"
    }
  },
  {
    "_id": {
      "$oid": "621767e082be3efa32ef43e0"
    },
    "l": {
      "$numberLong": "9007199254740993"
    }
  }
]

(The null, 2 bits here are just for prettier, more human-readable output by adding 2 spaces indentation.)

3 Likes

Thank you for the fast response and taking the time to write an extremely clear answer! That works perfectly.

I tried the EJSON within mongosh previously but must have messed it up.

1 Like

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.