Skip to content
Latchkey

mongosh --eval: Run MongoDB Commands in CI

mongosh --eval "<js>" connects, runs one JavaScript statement against the server, prints the result, and exits.

In a pipeline you rarely want the interactive shell. --eval lets a job run an insert, a count, or an admin command and capture the output as a step result.

What it does

mongosh --eval evaluates the given JavaScript against the target database and exits with the result on stdout. It is the non-interactive entry point for seeding data, checking counts, or issuing admin commands such as db.adminCommand({ ping: 1 }) from a CI step.

Common usage

Terminal
mongosh "mongodb://localhost:27017/test" --quiet \
  --eval 'db.users.insertOne({ name: "ci" })'
# print a count as plain output
mongosh --quiet --eval 'db.getSiblingDB("test").users.countDocuments()'
# run an admin command
mongosh --quiet --eval 'db.adminCommand({ ping: 1 }).ok'

Options

FlagWhat it does
--eval <js>Evaluate one JavaScript expression and exit
--quietSuppress the startup banner and connection chatter
--json[=relaxed|canonical]Print the result as EJSON instead of shell formatting
--host / --portTarget server when not using a connection string
-u / -p / --authenticationDatabaseCredentials and the auth source db
--norcSkip ~/.mongoshrc.js so CI is reproducible

In CI

Always pass --quiet so the banner does not pollute output you parse. Use --json=relaxed when a later step consumes the value, since the default shell formatting is not valid JSON. Wrap multi-statement logic in a function or use --file instead of cramming it into one --eval.

Common errors in CI

"MongoNetworkError: connect ECONNREFUSED 127.0.0.1:27017" means the mongod service container is not up yet; add a wait loop. "MongoServerError: command insert requires authentication" means you omitted -u/-p or the wrong --authenticationDatabase. A SyntaxError points at unescaped quotes in the shell; prefer single quotes around the --eval body.

Related guides

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