Skip to content
Latchkey

mongosh: Usage, Options & Common CI Errors

mongosh runs JavaScript and commands against a MongoDB server.

mongosh replaced the legacy mongo shell and is how pipelines seed and assert MongoDB state. Almost every CI failure is in the connection string: the host, the authSource, or the credentials.

What it does

mongosh connects to a MongoDB deployment using a connection string and runs JavaScript interactively or via --eval. In CI it points at a service container and is used to create users, seed data, or assert document counts.

Common usage

Terminal
mongosh "mongodb://localhost:27017/app" --eval 'db.users.countDocuments()'
mongosh "mongodb://user:pass@localhost:27017/app?authSource=admin" --eval 'db.runCommand({ping:1})'
mongosh --host 127.0.0.1 --port 27017 --quiet --eval 'db.adminCommand("ping")'
mongosh "mongodb://localhost:27017/app" seed.js

Options

Flag / itemWhat it does
"mongodb://..."Connection string (host, db, options)
--host / --portAlternative to the URI host/port
--eval "<js>"Run JavaScript and exit
-u / -pUsername / password
--authenticationDatabaseDatabase holding the credentials
--quietSuppress the startup banner

Common errors in CI

MongoServerError: Authentication failed. - credentials are wrong or the authSource is - users created in admin need ?authSource=admin (or --authenticationDatabase admin), not the app database. "MongoNetworkError: connect ECONNREFUSED 127.0.0.1:27017" means the server is not ready yet; loop on db.adminCommand("ping"). "MongoServerSelectionError ... getaddrinfo ENOTFOUND" is a bad host - in CI the service hostname, not localhost, may be required.

Related guides

Run this faster and cheaper on Latchkey managed runners. Start free →