There is no documentation on what db.stats().ok means on mongodb's site https://www.mongodb.com/docs/manual/reference/method/db.stats/.

For example I would like to check if the connection to the database is healthy. Can I do it like that db.stats().ok === 1. Is that correct for my purpose (looks like it, but without docs it's hard to tell), also is there a better way of checking for a healthy mongo connection?

1

Best Answer


I would suggest db.getMongo(). Command db.stats() requires read permissions on current database, which could be missing. In such case db.stats() would fail, despite your MongoDB is running fine.

db.getMongo() does not require any privileges, you can connect even without any credentials!

mongosh "mongodb://localhost:27017" --norc --quiet --eval 'db.getMongo()'mongodb://localhost:27017/?directConnection=true&serverSelectionTimeoutMS=2000&appName=mongosh+1.6.0echo $?0$ mongosh "mongodb://xxxx:27017" --norc --quiet --eval 'db.getMongo()'MongoNetworkError: getaddrinfo ENOTFOUND xxxxecho $?1