Different output in mongosh and mongo shells when creating indexes

Hi,
Im switching from the legacy mongo shell to mongosh and I have noticed that when creating indexes using db.collection.createIndex(...) the output varies from the previous shell. In the legacy version it used to return JSON structure with the "ok" key which allowed me to automatically validate the result of operation by just checking if its value is either 1 or 0, while in mongosh the return isn`t as consistent, since when succeeding it returns just a name of the index as a string and for example MongoServerError when I input invalid data. I wonder if this behavior is intended and whether there is any possibility to check the result of the operation in a similar way to the legacy shell.

Thanks for your time

2 Likes

Hi @Bartosz_Dabrowski1 and welcome to the community!!

The output change from legacy mongo to mongosh is an expected change. The later displays the index key getting created on success and throws an exception in case of an error.
The mongosh ticket has the details on the same.

In case you wish to display the output in the similar format, you could construct the command manually or write your own helper function:

db.foo.runCommand({ createIndexes: “mycollection”, indexes: [{key: { “bar”: 1}, name: “bar_1”}]})
{
createdCollectionAutomatically: true,
numIndexesBefore: 1,
numIndexesAfter: 2,
ok: 1
}

db.foo.runCommand({ createIndexes: “mycollection”, indexes: [{key: { “bar”: 1}, name: “bar_1”}]})
{
numIndexesBefore: 2,
numIndexesAfter: 2,
note: ‘all indexes already exist’,
ok: 1
}

Please let us know if you have any further questions.

Thanks
Aasawari

1 Like