Cheat Sheets

Install MongoDB on Debian 13 / 12 with mongosh Cheat Sheet

This post contains affiliate links. If you buy through them, we may earn a small commission at no extra cost to you. Learn more.

Debian 13 finally has its own MongoDB build. On our trixie test box the 9.0 packages came straight from the vendor trixie component (tested December 2026, MongoDB 9.0.8 on Debian 13), and a fresh mongod idled at 205 MB of resident memory while listening only on 127.0.0.1. The old workaround of pointing trixie at the bookworm repository is no longer needed for the current series.

Original content from computingforgeeks.com - post 121825

This guide installs MongoDB on Debian 13 and Debian 12, locks it down with authentication, opens it to one subnet, and backs it up. The second half is a mongosh cheat sheet: every row in the tables below was run on four lab machines (Debian 13, Debian 12, Ubuntu 26.04 and Rocky Linux 10), and each section shows the output we measured, including the two errors you will hit on purpose.

mongosh Cheat Sheet (Quick Reference)

The shell commands run from a Bash prompt on the server, and the rest run at a mongosh prompt after use storedb. Every row is a complete statement that we executed against MongoDB 9.0.8 with mongosh 2.14.3, so it can be pasted as is once you swap the database, collection and user names for your own.

Service and connection

CommandWhat it does
sudo systemctl enable --now mongodStart mongod and enable it at boot
sudo ss -tlnp | grep 27017Show which addresses mongod listens on
systemctl list-unit-files | grep mongodConfirm the unit is enabled
mongosh --quiet --eval 'db.version()'Print the server version without a session
mongosh -u mongoAdmin -p --authenticationDatabase adminLog in as the admin user (prompts for the password)
mongosh -u storeUser -p --authenticationDatabase storedb storedbLog in as an app user straight into its database
sudo journalctl -u mongod --no-pager -n 3Last systemd lines for the unit (mongod itself logs to /var/log/mongodb/mongod.log)

Databases and collections

CommandWhat it does
show dbsList databases with their size on disk
use storedbSwitch database (created on first write)
show collectionsList collections in the current database
db.createCollection("orders")Create an empty collection explicitly
db.orders.renameCollection("orders_archive")Rename a collection
db.orders_archive.drop()Drop a collection, returns true
db.getSiblingDB("scratch").dropDatabase()Drop another database without switching

Insert and query

CommandWhat it does
db.products.insertOne({ sku: "KB-114", name: "Mechanical Keyboard", category: "peripherals", price: 79.99, stock: 120 })Insert one document
db.products.find({ price: { $lt: 80 } }, { _id: 0, sku: 1, name: 1, price: 1 })Filter plus projection
db.products.findOne({ sku: "MS-220" })First matching document only
db.products.find({}, { _id: 0, name: 1, price: 1 }).sort({ price: -1 }).limit(2)Top two by price
db.products.countDocuments({ stock: { $gt: 100 } })Count matches
db.products.distinct("category")Unique values of a field
db.products.find({ name: { $regex: /ssd/i } }, { _id: 0, sku: 1, name: 1 })Case-insensitive pattern match
db.products.find({ category: { $in: ["storage", "audio"] } }, { _id: 0, sku: 1, category: 1 })Match any value in a list
db.products.find({ $or: [ { stock: { $lt: 80 } }, { price: { $gt: 90 } } ] }, { _id: 0, sku: 1, price: 1, stock: 1 })Either condition

Update and delete

CommandWhat it does
db.products.updateOne({ sku: "KB-114" }, { $inc: { stock: -5 } })Adjust a counter on one document
db.products.updateMany({ category: "peripherals" }, { $set: { onSale: true } })Set a field on every match
db.products.updateOne({ sku: "CB-001" }, { $set: { name: "USB-C Cable", category: "cables", price: 9.99, stock: 500 } }, { upsert: true })Update, or insert when missing
db.products.deleteOne({ sku: "CB-001" })Delete the first match
db.products.deleteMany({ stock: 0 })Delete every match

Indexes and aggregation

CommandWhat it does
db.products.createIndex({ sku: 1 }, { unique: true })Unique index, rejects duplicates with E11000
db.products.getIndexes()List indexes on a collection
db.products.createIndex({ category: 1, price: -1 })Compound index
db.products.dropIndex("category_1_price_-1")Drop an index by name
db.getSiblingDB("benchdb").events.find({ user: "u4242" }).explain("executionStats").executionStats.totalDocsExaminedDocuments scanned by a query (the Step 7 benchmark collection)
db.products.aggregate([ { $group: { _id: "$category", items: { $sum: 1 }, units: { $sum: "$stock" } } }, { $sort: { units: -1 } } ])Group and sum

Users and roles

CommandWhat it does
db.createUser({ user: "storeUser", pwd: passwordPrompt(), roles: [ { role: "readWrite", db: "storedb" } ] })App user scoped to one database
db.getUsers()Users defined in the current database
db.grantRolesToUser("storeUser", [ { role: "read", db: "reporting" } ])Add a role
db.revokeRolesFromUser("storeUser", [ { role: "read", db: "reporting" } ])Remove a role
db.runCommand({ connectionStatus: 1 }).authInfoWho you are logged in as, with roles

Server health

CommandWhat it does
db.stats(1024 * 1024)Database size figures in MiB
db.serverStatus().connectionsCurrent, available and rejected connections
db.adminCommand({ getParameter: 1, featureCompatibilityVersion: 1 })Feature compatibility version
db.currentOp({ active: true, secs_running: { $gte: 0 } }).inprog.lengthNumber of running operations
db.setProfilingLevel(1, { slowms: 50 })Log queries slower than 50 ms
db.getProfilingStatus()Current profiler level and threshold

Backup, restore, export

CommandWhat it does
mongodump -u mongoAdmin --authenticationDatabase admin --db storedb --out /backup/mongoBSON dump to a directory
mongodump -u mongoAdmin --authenticationDatabase admin --db storedb --gzip --archive=/backup/mongo/storedb.archive.gzSingle compressed archive file
mongorestore -u mongoAdmin --authenticationDatabase admin --nsInclude='storedb.*' --drop /backup/mongoRestore one database, replacing collections
mongorestore -u mongoAdmin --authenticationDatabase admin --gzip --archive=/backup/mongo/storedb.archive.gz --nsFrom='storedb.*' --nsTo='storedb_restore.*'Restore an archive under a new name
mongoexport -u mongoAdmin --authenticationDatabase admin --db storedb --collection products --type=csv --fields=sku,name,price --out /backup/mongo/products.csvExport chosen fields to CSV
mongoexport -u mongoAdmin --authenticationDatabase admin --db storedb --collection products --out /backup/mongo/products.jsonExport a collection to JSON
mongoimport -u mongoAdmin --authenticationDatabase admin --db storedb --collection products_copy --file /backup/mongo/products.jsonImport a JSON export

The four database tools in the last table take -u without -p and prompt on their own. Passing a bare -p the way mongosh accepts it fails with expected argument for flag '-p, --password', which is the first error we hit in the backup step.

What We Tested and the Numbers

Each lab machine was a 2 vCPU, 8 GB cloud VM with a 20 GB boot disk, installed from the official MongoDB repository for that distribution. The same 44 mongosh statements, the same backup commands and the same 200,000 document index test ran on all four, so the numbers below compare like with like. Each column was taken this way:

  • Idle RSS: ps -o rss=,cmd= -C mongod about one minute after the first start, before any user or data existed.
  • Unindexed and indexed query: executionTimeMillis and totalDocsExamined from explain("executionStats") for one user out of 5,000, before and after createIndex (Step 7).

Each figure is a single run per machine, so treat differences of a few milliseconds as noise from the shared cloud hosts rather than a property of the distro.

SystemRepository pathmongod idle RSSUnindexed queryIndexed query
Debian 13 (trixie)apt/debian trixie/mongodb-org/9.0 main205,448 KB68 ms, 200,000 docs0 ms, 40 docs
Debian 12 (bookworm)apt/debian bookworm/mongodb-org/9.0 main200,300 KB75 ms, 200,000 docs0 ms, 40 docs
Ubuntu 26.04apt/ubuntu resolute/mongodb-org/9.0 multiverse189,496 KB50 ms, 200,000 docs0 ms, 40 docs
Rocky Linux 10.2yum/redhat/10/mongodb-org/9.0204,904 KB51 ms, 200,000 docs0 ms, 40 docs

Idle memory sat within 16 MB across all four systems, so the distro choice makes no practical difference to footprint. The unindexed scan cost between 50 and 75 ms per run for 200,000 small documents. The index turned every one of them into a 40 document lookup that reported 0 ms. For the RHEL family the full walkthrough is in our guide to installing MongoDB on Rocky Linux and AlmaLinux, and Ubuntu has its own MongoDB server install guide. The repository steps we used on the Ubuntu 26.04 box match our walkthrough to install MongoDB on Ubuntu 26.04 or 24.04 from the official repo.

Prerequisites

MongoDB 9.0 targets x86_64 CPUs with AVX, and a CPU without it gets an Illegal instruction crash the moment mongod starts. Virtual machines with a generic CPU model (kvm64, qemu64) hide the flag even when the host has it, so check before installing anything:

grep -o avx /proc/cpuinfo | head -1

One line reading avx means the CPU qualifies. No output means the hypervisor is masking the flag, so change the VM CPU type to host and reboot before going further, because the packages install fine and only fail at the first start.

avx

Our 2 vCPU, 8 GB lab boxes are a floor for learning, not a production size. WiredTiger sizes its cache at 50% of (RAM minus 1 GB) by default, so production sizing starts from the working set (the documents and indexes hot queries touch) plus headroom for connections, at roughly 1 MB each. A small app database with a few GB of hot data runs well on 8 to 16 GB of RAM and SSD storage. MongoDB recommends XFS for WiredTiger, and the startup warnings will tell you so on ext4. You also need a sudo user and curl plus gnupg:

sudo apt update
sudo apt install -y gnupg curl

Both packages are usually present on a standard Debian install, in which case apt reports them as already the newest version. Minimal cloud images sometimes ship without gnupg, and the key import in Step 1 then fails because there is no gpg binary, so run this even if you think it is redundant.

Step 1: Add the MongoDB 9.0 Repository

MongoDB signs the 9.0 series with a key published as server-9.asc. There is no server-9.0.asc, and that URL returns 404, which trips up anyone adapting older 7.0 or 8.0 instructions. Import the key into its own keyring.

curl -fsSL https://www.mongodb.org/static/pgp/server-9.asc | sudo gpg --dearmor -o /usr/share/keyrings/mongodb-server-9.gpg

The repository line reads the codename from /etc/os-release, so the same command writes trixie on Debian 13 and bookworm on Debian 12:

echo "deb [ signed-by=/usr/share/keyrings/mongodb-server-9.gpg ] https://repo.mongodb.org/apt/debian $(. /etc/os-release && echo "$VERSION_CODENAME")/mongodb-org/9.0 main" | sudo tee /etc/apt/sources.list.d/mongodb-org-9.0.list

Read the file back before running apt. On the trixie box it holds the native component, and the signed-by path pins this repository to the MongoDB key alone, so a compromised key elsewhere on the system cannot sign packages for it.

deb [ signed-by=/usr/share/keyrings/mongodb-server-9.gpg ] https://repo.mongodb.org/apt/debian trixie/mongodb-org/9.0 main

The Debian 12 machine wrote the same line with bookworm in place of trixie, and both resolved to the same 9.0.8 packages. Because the codename is read at run time, the command also works unchanged in provisioning scripts that target both releases.

Debian 13 no longer borrows the bookworm build

Until the 9.0 series, MongoDB shipped no server packages for trixie, and Debian 13 guides (this one included) pointed the codename at bookworm. The 9.0 server package in the trixie component is a native build that depends on libssl3t64 from trixie instead of the bookworm libraries. The trixie/mongodb-org/8.0 and 8.2 components exist but hold only mongosh and the Atlas CLI (plus the database tools in 8.0), with no mongodb-org-server, so if your application is pinned to 8.0 on Debian 13, the bookworm line remains the only option and you should plan the move to 9.0 rather than run a cross-release build long term.

Choosing the version

New deployments should start on 9.0, the current major release with native packages for both Debian releases. Existing 8.0 servers upgrade one major at a time, and the feature compatibility version (FCV) has to reach the old major before the binaries change, and we read it later with getParameter. The 9.0 compatibility changes page lists what to check before an upgrade.

Step 2: Install mongodb-org

The mongodb-org metapackage pulls in the server, mongos, the mongosh shell and the database tools. Refresh the index so apt sees the new repository, then install:

sudo apt update
sudo apt install -y mongodb-org

Nine packages land. The seven mongodb-org components share one version, while mongodb-mongosh and mongodb-database-tools carry their own release numbers. Debian 13 has no MongoDB in its own archive, so every package comes from repo.mongodb.org, and a mismatch among the seven would mean a stale pin or a leftover list file from an older series. Filter the package list to check.

dpkg -l | grep mongodb-org

On Debian 13 every component reported 9.0.8.

ii  mongodb-org                            9.0.8                                amd64        MongoDB open source document-oriented database system (metapackage)
ii  mongodb-org-database                   9.0.8                                amd64        MongoDB open source document-oriented database system (metapackage)
ii  mongodb-org-database-tools-extra       9.0.8                                amd64        Extra MongoDB database tools
ii  mongodb-org-mongos                     9.0.8                                amd64        MongoDB sharded cluster query router
ii  mongodb-org-server                     9.0.8                                amd64        MongoDB database server
ii  mongodb-org-shell                      9.0.8                                amd64        MongoDB shell client
ii  mongodb-org-tools                      9.0.8                                amd64        MongoDB tools

The server and the shell carry separate version numbers, because mongosh ships on its own release train. That matters when you read bug reports or support threads, so record both.

mongod --version | head -1
mongosh --version

The server is 9.0.8 and the shell 2.14.3 on every machine we tested.

db version v9.0.8
2.14.3

The package installs a systemd unit but does not start it, unlike many Debian services. A reboot at this point would leave MongoDB stopped, so the next step enables it as well as starting it.

Step 3: Start mongod and Check the Listener

Enable the service so it survives a reboot and start it in the same command.

sudo systemctl enable --now mongod

The default /etc/mongod.conf binds to 127.0.0.1 only, so a fresh install is not reachable from the network. Confirm the bind address and the process memory:

sudo ss -tlnp | grep 27017
ps -o rss=,cmd= -C mongod

We measured one loopback listener and 205 MB of resident memory before any data existed.

dpkg, mongod --version and ss output showing MongoDB 9.0.8 installed and listening on 127.0.0.1:27017 on Debian 13

Treat that 205 MB as the empty baseline: resident memory grows as the WiredTiger cache fills with data and indexes, up to the cache limit set in Prerequisites. The first mongosh connection prints startup warnings worth reading once: on ext4 MongoDB recommends XFS, it flags that access control is not enabled yet, and it suggests a tcmalloc sysfs setting. Only the access control warning is a blocker, and Step 5 removes it.

Step 4: Create the Admin User

Create the administrator while authentication is still off, because after Step 5 an unauthenticated shell cannot create anyone. Open the shell with mongosh, then run the two statements below. passwordPrompt() asks for the password interactively so it never lands in your shell history:

use admin
db.createUser({ user: "mongoAdmin", pwd: passwordPrompt(), roles: [ { role: "userAdminAnyDatabase", db: "admin" }, { role: "readWriteAnyDatabase", db: "admin" }, { role: "dbAdminAnyDatabase", db: "admin" }, { role: "clusterMonitor", db: "admin" } ] })

The shell prints Enter password, masks the input, then confirms with { ok: 1 }. Pick a password you can type twice without error, because a typo here leaves an admin account nobody can log in with once Step 5 turns on authentication.

test> use admin
switched to db admin
admin> db.createUser({ user: "mongoAdmin", pwd: passwordPrompt(), roles: [ { role: "userAdminAnyDatabase", db: "admin" }, { role: "readWriteAnyDatabase", db: "admin" }, { role: "dbAdminAnyDatabase", db: "admin" }, { role: "clusterMonitor", db: "admin" } ] })
Enter password
*********************{ ok: 1 }
admin> exit

These four roles cover user management, data access, index and stats work, plus read access to server metrics. Be clear about what that means, though. The MongoDB docs call userAdminAnyDatabase effectively a system superuser, because the account can grant itself any role, so guard this password as you would a root one. Leaving out root only keeps shutdown and replication commands out of everyday sessions. Our guide to MongoDB authentication covers the role model in more depth.

Step 5: Enable Authentication

The shipped config has the security section commented out at line 28, which is why the server accepted the anonymous shell in Step 4. Open the file.

sudo vim /etc/mongod.conf

Replace the #security: line with this block. YAML is indentation sensitive, so use two spaces, never a tab:

security:
  authorization: enabled

Save the file, check the two lines landed, and restart the service.

grep -A1 '^security' /etc/mongod.conf
sudo systemctl restart mongod

We hit a timing trap on the first run. systemctl is-active mongod already answered active, yet a mongosh call fired immediately afterwards failed with MongoNetworkError: connect ECONNREFUSED 127.0.0.1:27017, because the unit counts as started before the port is listening. In scripts, wait for the socket instead of sleeping a guessed number of seconds:

until sudo ss -tln | grep -q ':27017'; do sleep 1; done

Once the port is up, an anonymous call is refused and the admin login shows the four roles from Step 4:

mongosh --quiet --eval 'db.adminCommand({ listDatabases: 1 })'
mongosh -u mongoAdmin -p --authenticationDatabase admin --quiet --eval 'db.runCommand({ connectionStatus: 1 }).authInfo'

The screenshot shows the whole sequence on the Debian 13 box. The refused connection right after the restart is the race described above, and the second attempt a moment later reached the server and was turned away for lack of credentials.

mongosh showing ECONNREFUSED right after restart, then requires authentication, then mongoAdmin roles after login

Command listDatabases requires authentication is the answer you want from an anonymous shell. If listDatabases still returns data, the edit was not saved or the restart never happened: a YAML error stops mongod from starting at all rather than running it with auth off. Once you can log in as mongoAdmin, db.adminCommand({ getCmdLineOpts: 1 }).parsed prints the settings the running process actually loaded.

Step 6: Create an App User and Run Queries

Applications should never connect as mongoAdmin. Log in as the admin, switch to the app database and create a user whose only role is readWrite on that database:

mongosh -u mongoAdmin -p --authenticationDatabase admin

At the test> prompt, switch database and create the user. The database does not exist until the first write, so use storedb on its own creates nothing:

use storedb
db.createUser({ user: "storeUser", pwd: passwordPrompt(), roles: [ { role: "readWrite", db: "storedb" } ] })
db.getUsers()

getUsers() confirms the scope and shows that MongoDB stores both SCRAM mechanisms for the account:

{
  users: [
    {
      _id: 'storedb.storeUser',
      userId: UUID('d1b82acf-2a51-4a48-9508-4a43725e4830'),
      user: 'storeUser',
      db: 'storedb',
      roles: [ { role: 'readWrite', db: 'storedb' } ],
      mechanisms: [ 'SCRAM-SHA-1', 'SCRAM-SHA-256' ]
    }
  ],
  ok: 1
}

Seed the collection with four products. insertMany returns one ObjectId per document, which is how you know all of them were written:

db.products.insertOne({ sku: "KB-114", name: "Mechanical Keyboard", category: "peripherals", price: 79.99, stock: 120 })
db.products.insertMany([ { sku: "MS-220", name: "Wireless Mouse", category: "peripherals", price: 24.5, stock: 340 }, { sku: "HD-870", name: "NVMe SSD 1TB", category: "storage", price: 92, stock: 75 }, { sku: "HS-310", name: "USB Headset", category: "audio", price: 49, stock: 0 } ])

A filter with a projection is the query shape most apps run. The second argument keeps only the fields named, and _id: 0 drops the ObjectId:

storedb> db.products.find({ price: { $lt: 80 } }, { _id: 0, sku: 1, name: 1, price: 1 })
[
  { sku: 'KB-114', name: 'Mechanical Keyboard', price: 79.99 },
  { sku: 'MS-220', name: 'Wireless Mouse', price: 24.5 },
  { sku: 'HS-310', name: 'USB Headset', price: 49 }
]
storedb> db.products.find({ $or: [ { stock: { $lt: 80 } }, { price: { $gt: 90 } } ] }, { _id: 0, sku: 1, price: 1, stock: 1 })
[
  { sku: 'HD-870', price: 92, stock: 75 },
  { sku: 'HS-310', price: 49, stock: 0 }
]

Updates return counters rather than documents. matchedCount against modifiedCount tells you whether a filter found nothing or found documents that already had the value, and an upsert reports the new insertedId:

storedb> db.products.updateOne({ sku: "KB-114" }, { $inc: { stock: -5 } })
{
  acknowledged: true,
  insertedId: null,
  matchedCount: 1,
  modifiedCount: 1,
  upsertedCount: 0
}
storedb> db.products.updateMany({ category: "peripherals" }, { $set: { onSale: true } })
{
  acknowledged: true,
  insertedId: null,
  matchedCount: 2,
  modifiedCount: 2,
  upsertedCount: 0
}
storedb> db.products.updateOne({ sku: "CB-001" }, { $set: { name: "USB-C Cable", category: "cables", price: 9.99, stock: 500 } }, { upsert: true })
{
  acknowledged: true,
  insertedId: ObjectId('6b0d0f647ad11455d946b4d8'),
  matchedCount: 0,
  modifiedCount: 0,
  upsertedCount: 1
}
storedb> db.products.deleteOne({ sku: "CB-001" })
{ acknowledged: true, deletedCount: 1 }
storedb> db.products.deleteMany({ stock: 0 })
{ acknowledged: true, deletedCount: 1 }

A unique index enforces business keys at the database layer. The duplicate insert below is the first of the two errors we triggered on purpose:

storedb> db.products.createIndex({ sku: 1 }, { unique: true })
sku_1
storedb> db.products.insertOne({ sku: "KB-114", name: "Duplicate Keyboard" })
Uncaught MongoServerError: E11000 duplicate key error collection: storedb.products index: sku_1 dup key: { sku: "KB-114" }

Aggregation does the reporting work that would otherwise happen in application code. This pipeline groups by category and sums stock. The second multiplies price by stock, and the long decimal in its output is IEEE floating point at work, so store money as Decimal128 or integer cents if exact totals matter.

storedb> db.products.aggregate([ { $group: { _id: "$category", items: { $sum: 1 }, units: { $sum: "$stock" } } }, { $sort: { units: -1 } } ])
[
  { _id: 'peripherals', items: 2, units: 455 },
  { _id: 'storage', items: 1, units: 75 }
]
storedb> db.products.aggregate([ { $match: { onSale: true } }, { $project: { _id: 0, name: 1, stockValue: { $multiply: ["$price", "$stock"] } } } ])
[
  { name: 'Mechanical Keyboard', stockValue: 9198.849999999999 },
  { name: 'Wireless Mouse', stockValue: 8330 }
]

The terminal capture below is that same admin session, running the count, distinct and sort rows from the cheat sheet before it hits the unique index error and the group stage:

mongosh session on MongoDB 9.0.8 running countDocuments, distinct, sort, a unique index E11000 error and a group aggregation

Back at the Bash prompt, prove the app user is scoped correctly. It can count its own collection, and reading the admin user table is refused:

mongosh -u storeUser -p --authenticationDatabase storedb storedb --quiet --eval 'db.products.countDocuments()'
mongosh -u storeUser -p --authenticationDatabase storedb storedb --quiet --eval 'db.getSiblingDB("admin").system.users.findOne()'

Three products remain after the deletes, and the cross-database read fails as designed. If the second command ever returns a document, the user was created in the wrong database or with a broader role.

Enter password: *********************
3
Enter password: *********************
MongoServerError: not authorized on admin to execute command { find: "system.users", filter: {}, limit: 1, lsid: { id: UUID("7b8b7b29-1a47-4db1-972b-68e1c4ef24e9") }, $db: "admin" }

A wrong password returns a flat MongoServerError: Authentication failed. with no hint about whether the user exists, and mongod logs each attempt as Failed to authenticate. If you prefer to explore the data in a GUI, MongoDB Compass on Debian connects with the same storeUser credentials. For the longer treatment of document modelling and pipelines, MongoDB in Action, Third Edition is the book we would hand a developer new to MongoDB.

Step 7: Measure What an Index Buys

Four products are too few to show anything, so we loaded 200,000 event documents spread across 5,000 users and timed the lookup for one user with explain("executionStats") before and after indexing. In a mongoAdmin session, create the test data first:

use benchdb
db.events.insertMany(Array.from({ length: 200000 }, (_, i) => ({ n: i, user: "u" + (i % 5000), ts: new Date(Date.now() - i * 1000) }))).acknowledged

Then read the scan count and the time for the same query twice, with createIndex in between:

db.events.find({ user: "u4242" }).explain("executionStats").executionStats.totalDocsExamined
db.events.find({ user: "u4242" }).explain("executionStats").executionStats.executionTimeMillis
db.events.createIndex({ user: 1 })
db.events.find({ user: "u4242" }).explain("executionStats").executionStats.totalDocsExamined
db.events.find({ user: "u4242" }).explain("executionStats").executionStats.executionTimeMillis
db.events.find({ user: "u4242" }).explain("executionStats").queryPlanner.winningPlan.inputStage.stage

Debian 13 scanned every document in 68 ms without the index, and examined exactly the 40 matching documents in under a millisecond with it:

mongosh explain executionStats before and after createIndex on a 200000 document collection, 200000 docs examined dropping to 40

The ratio is the result to keep: 200,000 documents examined against 40 is a 5,000x cut in work, and the collection scan grows linearly with the data while the IXSCAN stays flat. Across the four systems the scan measured 50 to 75 ms, a spread that reflects the cloud hosts more than the distros. The rule we apply is simple: any query in a hot path whose totalDocsExamined is far above nReturned needs an index, and the profiler in the last section finds those queries for you. Drop the test data with db.dropDatabase() while still in benchdb.

Step 8: Allow Remote Connections from One Subnet

Keep MongoDB on loopback unless an application on another host needs it. When one does, add the private address of the server to bindIp and let the firewall decide who reaches the port. Our server is 10.0.1.50 and the app servers live in 10.0.1.0/24, so substitute your own values. Use an address the host really has (ip -4 addr lists them), because mongod refuses to start when bindIp names one it cannot bind. Open the config again:

sudo vim /etc/mongod.conf

In the net section, append the private address to the existing loopback entry so local admin access keeps working:

net:
  port: 27017
  bindIp: 127.0.0.1,10.0.1.50

Restart, wait for the port, and confirm mongod now holds two listeners:

sudo systemctl restart mongod && until sudo ss -tln | grep -q ':27017'; do sleep 1; done; sudo ss -tlnp | grep 27017

Both addresses are bound by the same process. Binding 0.0.0.0 would also work, but it exposes the port on every interface the host ever gains, including a public one added later.

LISTEN 0      4096   10.0.1.50:27017      0.0.0.0:*    users:(("mongod",pid=4381,fd=9))
LISTEN 0      4096       127.0.0.1:27017      0.0.0.0:*    users:(("mongod",pid=4381,fd=10))

Debian ships no firewall by default. Install UFW, allow SSH before enabling it so the session survives, and open 27017 to the app subnet only. The OpenSSH profile covers port 22, so if sshd listens elsewhere, add sudo ufw allow <port>/tcp for it first or the enable step locks you out:

sudo apt install -y ufw
sudo ufw allow OpenSSH
sudo ufw allow from 10.0.1.0/24 to any port 27017 proto tcp
sudo ufw --force enable
sudo ufw status verbose

The default policy denies everything else inbound, so a host outside 10.0.1.0/24 gets no answer on 27017 even though mongod listens on the address.

Status: active
Logging: on (low)
Default: deny (incoming), allow (outgoing), disabled (routed)
New profiles: skip

To                         Action      From
--                         ------      ----
22/tcp (OpenSSH)           ALLOW IN    Anywhere
27017/tcp                  ALLOW IN    10.0.1.0/24
22/tcp (OpenSSH (v6))      ALLOW IN    Anywhere (v6)

The capture below shows both halves together on the Debian 13 server: the two listeners from the bindIp change, then the three ufw rules with 27017 limited to the app subnet.

mongod listening on 127.0.0.1 and 10.0.1.50 with ufw allowing 27017 only from 10.0.1.0/24 on Debian 13

From a client in the subnet (our Debian 12 box, with the mongodb-mongosh package installed from the MongoDB repository, bookworm component), connect with a URI. A # in the password must be written as %23 or the driver reads the rest as a URL fragment, and single quotes stop Bash from treating the ! as history expansion:

mongosh 'mongodb://mongoAdmin:Str0ng!AdminPass%[email protected]:27017/admin' --quiet --eval 'db.runCommand({ ping: 1 })'

The remote ping answered { ok: 1 }. Passwords in URIs end up in shell history and process listings, so for anything beyond a connectivity test use -u with -p and let mongosh prompt, and add TLS before the traffic crosses an untrusted network.

Step 9: Back Up and Restore with mongodump

Create a backup directory owned by your login user, so the tools can write there without sudo:

sudo mkdir -p /backup/mongo && sudo chown "$USER": /backup/mongo

Our first attempt used -u mongoAdmin -p --authenticationDatabase admin, copied from the mongosh commands above, and every tool refused it with error parsing command line options: expected argument for flag '-p, --password', but got option '--authenticationDatabase'. The database tools treat -p as needing a value, so leave it out and they prompt with Enter password for mongo user:. A directory dump and a compressed archive look like this:

mongodump -u mongoAdmin --authenticationDatabase admin --db storedb --out /backup/mongo
mongodump -u mongoAdmin --authenticationDatabase admin --db storedb --gzip --archive=/backup/mongo/storedb.archive.gz

To test the restore for real, we dropped the products collection and brought it back. --nsInclude limits the restore to one database and --drop replaces existing collections instead of merging into them:

mongorestore -u mongoAdmin --authenticationDatabase admin --nsInclude='storedb.*' --drop /backup/mongo

All three documents came back. We had reseeded the collection between runs, so the product names in the screenshot are spelled slightly differently from Step 6, and mongorestore also prints harmless “don’t know what to do with file … skipping” lines for the archive, the CSV and JSON exports and the prelude.json of the dump in the same directory. The screenshot also shows a CSV export of the same collection, made with the mongoexport row from the cheat sheet.

mongodump writing storedb.products and mongorestore restoring 3 documents with nsInclude and drop

Three results from that run change how we would set up backups on a real server:

  • Restore under a new name: the archive restore with --nsFrom='storedb.*' --nsTo='storedb_restore.*' wrote 3 documents into storedb_restore, which is the safe way to inspect a backup next to live data.
  • Deprecated flags: the older --db storedb --dir form still restored, but printed a warning to use --nsInclude instead, so scripts written for older tools need updating.
  • Size: the dump directory, archive and exports totalled 32 KB here. On real data, run the dump from cron and copy it off the host, because a backup on the same disk protects against mistakes, not against losing the disk.

Test a restore on a schedule as well. A dump that has never been restored is an assumption, and the drop and restore above took under a second for this collection, so there is no cost argument against doing it.

What to Watch in the mongod Metrics

A running server tells you most of what goes wrong before users do, if you read the right counters. These are the four we check first on any MongoDB host, with the values from our idle Debian 13 box as a baseline:

  • Connections: db.serverStatus().connections reported current: 4 and available: 25596 with rejected: 0. A climbing current with flat traffic means an app is leaking connections, and any non-zero rejected means clients are already failing.
  • Slow queries: db.setProfilingLevel(1, { slowms: 50 }) moved the threshold from the default 100 ms to 50 ms. The profiler then records every slower operation in system.profile, which is where unindexed scans like the 68 ms one in Step 7 show up.
  • Feature compatibility: getParameter returned featureCompatibilityVersion: { version: '9.0' }. Check it before every major upgrade, because the next major’s binaries only start on data whose FCV already matches the current major.
  • Failed logins: sudo grep -c 'Failed to authenticate' /var/log/mongodb/mongod.log counted the single wrong password we sent during testing. On a server bound to a network address, a count that rises overnight is someone guessing.

For anything beyond a single server, scrape these counters into a time series rather than polling them by hand. Our setup for monitoring MongoDB with Prometheus and Grafana graphs connections, operation latency and cache use. The single-node install also has no replica set, so rs.status() fails with NoReplicationEnabled: not running with --replSet. That is the second deliberate error from our session, and it is the reason a standalone mongod should not hold data you cannot restore from the dumps in Step 9.

Keep reading

Install Samba on Debian 13 / 12 and Create a File Share Debian Install Samba on Debian 13 / 12 and Create a File Share Claude Code Cheat Sheet: Commands, Shortcuts and Flags (PDF) AI Claude Code Cheat Sheet: Commands, Shortcuts and Flags (PDF) Backup and Restore Linux Systems with Timeshift Debian Backup and Restore Linux Systems with Timeshift netsh Commands Cheat Sheet: Wi-Fi, Firewall, Port Proxy (PDF) Cheat Sheets netsh Commands Cheat Sheet: Wi-Fi, Firewall, Port Proxy (PDF) VS Code Keyboard Shortcuts Cheat Sheet (Windows, Mac, Linux PDF) Cheat Sheets VS Code Keyboard Shortcuts Cheat Sheet (Windows, Mac, Linux PDF) How to deploy Redis StatefulSet Cluster in Kubernetes Cloud How to deploy Redis StatefulSet Cluster in Kubernetes

2 thoughts on “Install MongoDB on Debian 13 / 12 with mongosh Cheat Sheet”

  1. Hi Klinsmann Öteyo, a very nice and detailed article, unfortunately this does not work on our Raspberry Pi 4B Rev 1.4 with 8GB, SSD and with an ARMv7 Processor rev 3 (v7l).
    We get the error message when running the update command that our Processor is not supported by the repo.
    Do you know or have of any practical solution?
    Greetings Heinz

    Reply

Leave a Comment

Press ESC to close