Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Some links on this page are affiliate links: if you buy through them we may earn a commission, at no extra cost to you.

For current MongoDB shell work, connect with mongosh, then use collection methods for CRUD and queries, aggregation pipelines for transformations, and db.runCommand() or db.adminCommand() when you need to send a command document to the server. The 48 examples below assume an authenticated, connected shell and use db.users as a sample collection. Replace database names, collections, fields, and credentials with your own values; check command support for your MongoDB server version and deployment before production use.

Connect to a deployment and inspect your context

Start by connecting to the deployment you intend to use. MongoDB’s run-commands guidance says you must connect before running commands in mongosh. The show commands are shell conveniences; methods such as db.getSiblingDB() and command methods provide programmable alternatives.

Connect and switch databases

  1. mongosh "mongodb+srv://<cluster>/<db>" — connect using a deployment connection string. Replace the placeholders with your cluster and database details. Protect credentials and use your deployment’s approved authentication settings.
  2. db — print the current database context.
  3. use <database> — switch the shell context to another database.
  4. db.getSiblingDB("<database>") — reference another database without changing the current context. This is useful in scripts that work across databases.

List databases and collections

  • show dbs — list databases visible to the authenticated user. An empty or partial result can reflect privileges rather than an absence of databases.
  • show collections — list collections in the current database using a shell helper.
  • db.getCollectionNames() — return collection names as an array, which is convenient for scripts.
  • db.listCollections().toArray() — retrieve collection metadata through a cursor and materialize it as an array.

Create, read, update, and delete documents

CRUD methods are collection methods. Inserts can create a collection implicitly: MongoDB creates it when the first document is stored if it does not already exist. Before writes or deletes in a live database, verify the selected database and filter; a broad filter can affect more documents than intended.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Insert documents

  • db.users.insertOne({name:"Ada",active:true}) — insert one document.
  • db.users.insertMany([{name:"Ada"},{name:"Lin"}]) — insert multiple documents in one operation. Review the input and error-handling behavior when processing a batch.

Read and count

  • db.users.find({active:true}) — return documents matching a filter.
  • db.users.findOne({name:"Ada"}) — return one matching document, or no document if there is no match.
  • db.users.countDocuments({active:true}) — count documents matching a filter.
  • db.users.distinct("role") — return distinct values for a field.

Update and replace

  • db.users.updateOne({name:"Ada"},{$set:{active:false}}) — update the first document matching the filter. The $set operator changes the named field rather than replacing the whole document.
  • db.users.updateMany({active:false},{$set:{status:"inactive"}}) — update every matching document. Check the filter carefully before running it against production data.
  • db.users.replaceOne({name:"Ada"},{name:"Ada",active:true}) — replace one matching document with the replacement document. Include every field you intend to retain; this is not a partial update.

Delete and combine writes

  • db.users.deleteOne({name:"Ada"}) — delete one matching document.
  • db.users.deleteMany({active:false}) — delete all matching documents. Treat this as destructive: confirm the filter and scope before execution.
  • db.users.bulkWrite([{insertOne:{document:{name:"Kai"}}},{updateOne:{filter:{name:"Lin"},update:{$set:{active:true}}}}]) — combine write operations into one bulk request. Validate every operation in the batch; bulk execution does not make a mistaken operation harmless.

Shape queries and build aggregation pipelines

Use a normal find query when you need matching documents with straightforward sort, limit, or projection behavior. Use aggregate() when documents must pass through an ordered sequence of transformations. Pipeline stage order matters: filter early when practical, then sort, group, reshape, or join as the result requires.

Filter, sort, limit, and project

  • db.users.find({age:{$gte:18}}).sort({age:-1}).limit(20) — select documents with age at least 18, sort by age descending, and return at most 20 results.
  • db.users.find({name:/^A/},{name:1,_id:0}) — match names beginning with A and project only name, excluding _id. Consider the size of the collection and available indexes when using regex filters.

Transform, group, and join

  • db.users.aggregate([{$match:{active:true}}]) — start a pipeline by retaining active users.
  • db.orders.aggregate([{$group:{_id:"$status",count:{$sum:1}}}]) — group orders by status and count documents in each group.
  • db.orders.aggregate([{$match:{total:{$gt:100}}},{$sort:{total:-1}}]) — filter orders above 100 before sorting the remaining documents by total descending.
  • db.orders.aggregate([{$unwind:"$items"}]) — expand an array field so each array element is represented in a separate pipeline document. Decide how missing, null, or empty arrays should be handled for your use case.
  • db.orders.aggregate([{$lookup:{from:"users",localField:"userId",foreignField:"_id",as:"user"}}]) — match related user documents from the users collection and place matches in the user array.
  • db.users.aggregate([{$project:{name:1,year:{$year:"$createdAt"}}}]) — retain the name and calculate a year field from createdAt. Ensure the source field contains compatible date values.
  • db.users.aggregate([{$set:{normalizedName:{$toLower:"$name"}}}]) — add or transform a field in pipeline output by converting the name to lowercase.

Write pipeline output

db.users.aggregate([{$out:"usersArchive"}]) — write pipeline results to the usersArchive collection. This has a write effect, so confirm permissions, destination, data-retention expectations, and operational impact before running it.

Create indexes and inspect query execution

Indexes shape the access paths MongoDB can use to find and order data. They can improve some reads but consume storage and add work to writes. Use query plans to check how a query actually executes rather than assuming that an index is selected.

Build, list, and remove indexes

  • db.users.createIndex({email:1},{unique:true}) — create a unique ascending index on email. Existing duplicate values can prevent a unique index from being created.
  • db.users.createIndexes([{age:1},{status:1,createdAt:-1}]) — request multiple indexes, including a compound index with descending order on createdAt.
  • db.users.getIndexes() — list indexes for the collection.
  • db.users.listIndexes().toArray() — read index metadata from a cursor as an array.
  • db.users.dropIndex("email_1") — remove an index by name. Confirm that it is safe to remove; this can change query performance and available constraints.
  • db.users.hideIndex("status_1") — hide an index for planner testing where the deployment and server version support the operation. Verify support before relying on it.

Explain a query and test a hint

  • db.users.find({email:"[email protected]"}).explain("executionStats") — inspect the selected plan and execution statistics for a query shape.
  • db.users.find({status:"open"}).hint({status:1}) — force a candidate index for controlled testing. A hint can make performance worse if the chosen index is unsuitable; compare behavior and avoid treating it as a default fix.
  • db.runCommand({explain:{find:"users",filter:{status:"open"}},verbosity:"executionStats"}) — request explain information using the command form. Use this form when you need the server-command interface or a query shape expressed as a command document.

Use sessions, transactions, and database roles

Transactions are session-scoped: start a session, start the transaction, perform the intended work through that session, and explicitly commit or abort. Transaction availability and behavior depend on deployment configuration. Create users with the narrowest role set that supports their work.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Start and commit a transaction

  1. const session=db.getMongo().startSession(); session.startTransaction() — start a client session and transaction. Operations that belong to the transaction must use the session.
  2. session.commitTransaction() — commit after the transaction’s writes have succeeded and the result is ready to be made durable. If the work fails, abort rather than committing partial intent; use session.abortTransaction() where appropriate.

Create a user and grant a role

  • db.createUser({user:"app",pwd:passwordPrompt(),roles:[{role:"readWrite",db:"appdb"}]}) — create an application user with read/write access scoped to appdb. The prompt avoids putting the password literal in shell history.
  • db.grantRolesToUser("app",[{role:"read",db:"reporting"}]) — add read access on the reporting database to an existing user. Review role scope as part of access control changes.

Check server health, operations, and replication

Administrative commands can reveal instance-wide status or operational details and may require elevated privileges. Run them against the intended deployment and interpret results in the context of whether it is self-managed or hosted.

  • db.adminCommand({ping:1}) — test whether a server command can reach the deployment. A successful ping establishes command responsiveness, not that every application dependency is healthy.
  • db.serverStatus() — inspect instance-wide resource and status metrics. The output is broad; focus on the metrics relevant to the symptom being investigated.
  • db.currentOp() — inspect operations currently in progress. Use it to investigate active work, while treating any follow-up intervention as a separate operational decision.
  • db.adminCommand({replSetGetStatus:1}) — inspect replica-set status where supported and authorized.
  • db.adminCommand({listDatabases:1}) — list databases with basic statistics when the authenticated account is authorized to do so.

Check support and avoid common failures

MongoDB command availability is not identical across all server versions and deployment types. The official command reference identifies support notes and version information for many commands; check the entry for your specific command, server version, and Atlas tier or self-managed deployment before adopting it.

Common symptoms and fixes

  • Authentication or authorization error: confirm the connection string, authentication settings, target database, and required role. A command such as listDatabases may need privileges not granted to an application user.
  • Command or method unavailable: verify that the method exists in your shell/server combination and that your deployment supports the operation. Atlas support and server-version availability can differ.
  • No documents returned: check the current database, collection name, field spelling, value type, and filter. For aggregation, inspect each stage in sequence.
  • Write changes more data than expected: stop and inspect the filter and target context. In particular, review updateMany(), deleteMany(), $out, and transaction commits before running them on important data.
  • Unique index creation fails: inspect existing values for duplicates and resolve them before retrying the unique index build.
  • Query is unexpectedly slow: inspect explain("executionStats"), query selectivity, sort behavior, and index choice. Test hints only in a controlled way.
  • Transaction fails or cannot start: confirm transaction support for the deployment and ensure transaction operations use the session; explicitly abort failed work.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Or skip the browser setup

If a development task also needs a website screenshot, ScreenshotNeo offers a one-request API and an MCP server for AI agents. The request below uses the supplied cURL example; replace the target URL and API key with your own. See the ScreenshotNeo API documentation for options.

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
  • Cookie and consent banners, newsletter popups, and chat widgets are removed before capture; each cleanup step can be turned off.
  • Bot checks or CAPTCHAs, blank pages, timeouts, failed loads, and cache hits are not billed; response headers report the page verdict and billing status.
  • The MCP server provides take_screenshot, get_page_info, and capture_pdf for Claude, Cursor, and other MCP clients.
  • The free plan includes 1,000 screenshots per month with no card; paid plans start at $5 for 3,000 shots.

Sign up for ScreenshotNeo’s free plan to get 1,000 screenshots a month with no card.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.