Workarounds for functions which are not available in new mongosh

For the new mongosh the documentation states:

Currently mongosh supports a subset of the mongo shell methods. Achieving feature parity between mongosh and the mongo shell is an ongoing effort.

I think it makes sense to provide a common thread of workarounds with functions which are available in legacy mongo shell but not in new mongosh. For some functions the developers already decided not migrating them.

Let’s start with these ones:

tojsononeline (no documentation found):

function tojsononeline(x) {
   return JSON.stringify(x, (key, value) => { return value; }, ' ');
}

hostname() :

os.hostname()

Object.bsonsize() :

const bson = require("bson");
new bson.BSONPure.BSON().calculateObjectSize(doc)

_getEnv(<variable>) (not documented):

process.env[<variable>]

Feel free to add some more.

Wernfrieed

1 Like

Hi @Wernfried_Domscheit,

thank you for sharing your workarounds for some of the legacy functions that are not available in mongosh.

It’s worth mentioning that some of this functionality is available in a shell snippet that can be installed from within mongosh with

> snippet install mongocompat

I am curious: are you looking at having these functions defined in mongosh because they are used in a number of scripts that are part of your day-to-day work or because of muscle memory when you work with the shell interactively?

1 Like

Hi Massimiliano

hostname() and tojsononeline() are part of my application scripts. They are used for logging purpose.

I skipped using _getEnv() because it is not documented. Otherwise I would use it also in my application. Currently I use rather --eval "const HOME = ${HOME}" if I need to read environment variables.

Kind Regards
Wernfried

1 Like

Hi @Wernfried_Domscheit, MongoSH is also a node.js environment.

I’m not sure if this is going to help as you may have a lot of code to convert but here are some alternatives:

hostname()

require("os").hostname();

tojsononeline()

const jsonString = EJSON.stringify(obj);

_getEnv()

const home = process.env.HOME;
2 Likes