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.
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 mikechenViewing Databases
List all databases on the server with:
show dbsDeleting 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({})Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Mike Chen's Internet Architecture
Over ten years of BAT architecture experience, shared generously!
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
