Wait for MongoDB to Be Ready in CI (mongosh ping)
A short loop running mongosh --eval "db.adminCommand({ ping: 1 })" blocks until MongoDB answers, so tests do not start against a server that is still booting.
A mongod service container reports the port open before it can serve queries. Pinging in a loop is the reliable readiness gate.
What it does
The ping admin command is the lightest way to confirm the server is accepting commands. Running it in a retry loop turns "is MongoDB up" into a clean exit code: keep trying until ping succeeds or a timeout is hit, then fail the job rather than the test suite.
Common usage
for i in $(seq 1 30); do
mongosh --quiet --eval 'db.adminCommand({ ping: 1 })' \
"mongodb://localhost:27017" && break
echo "waiting for mongodb ($i)"; sleep 2
doneGitHub Actions service container
services:
mongo:
image: mongo:7
ports: ['27017:27017']
options: >-
--health-cmd "mongosh --quiet --eval 'db.adminCommand({ping:1}).ok'"
--health-interval 10s
--health-timeout 5s
--health-retries 5In CI
Prefer the service container --health-cmd so the runner waits before the job step even starts; the shell loop is a fallback when you need extra control. Newer images ship mongosh; very old mongo images only have the legacy mongo binary, so the health command must match what the image actually contains.
Common errors in CI
"MongoNetworkError: connect ECONNREFUSED" on the first iterations is expected while booting; the loop should swallow it. If every attempt fails, the port mapping is wrong or the container exited (check docker logs). "mongosh: command not found" inside a health-cmd means the image has only mongo; switch the command accordingly.