Databases 4 min read

Master MongoDB: Essential Commands for Creating, Querying, and Managing Databases

This guide walks you through the core MongoDB commands—including creating and switching databases, listing databases, inserting, updating, querying (with filters, pagination, distinct, and fuzzy search), counting records, and deleting documents—providing concise examples for each operation.

Mike Chen's Internet Architecture
Mike Chen's Internet Architecture
Mike Chen's Internet Architecture
Master MongoDB: Essential Commands for Creating, Querying, and Managing Databases

Creating and Switching Databases

Use the use DATABASE_NAME command to switch to an existing database or create a new one if it does not exist.

use mikechen

Viewing Databases

List all databases on the server with:

show dbs

Deleting a Database

Switch to the target database and then drop it:

use DATABASE_NAME
db.dropDatabase()

Inserting Documents

Insert a document into a collection using insert:

db.users.insert({
  name: "小张",
  age: 19,
  gender: 1,
  address: "广州",
  isDelete: 0
})

Updating Documents

Update matching documents with update and the $set operator (similar to SQL UPDATE):

db.users.update({username: "smith"}, {$set: {country: "Canada"}})

Querying Documents

Retrieve all records: db.users.find() Count the total number of records: db.users.find().count() Get distinct values for a field: db.users.distinct("name") Conditional query (e.g., age equals 28): db.users.find({"age": 28}) Pagination (limit and skip):

db.users.find().limit(5).skip(2)

Fuzzy Search

Find documents where the name field matches a regular expression:

db.users.find({name: /mikechen/})

Deleting Documents

Remove all documents from a collection: db.products.remove({}) Remove documents matching a condition (e.g., age greater than 20): db.users.remove({age: {$gt: 20}}) Delete all documents in a collection using deleteMany:

db.collection.deleteMany({})
Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

CRUDMongoDBNoSQLqueryDatabase Commands
Mike Chen's Internet Architecture
Written by

Mike Chen's Internet Architecture

Over ten years of BAT architecture experience, shared generously!

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.