Databases 17 min read

Master MongoDB: Essential CRUD, Queries, Tools, and User Management Guide

This comprehensive tutorial covers MongoDB fundamentals, including CRUD operations, display commands, conditional queries, updates, deletions, essential tools like mongod and mongostat, authentication mechanisms, role definitions, configuration settings, and step‑by‑step user and admin creation for secure database management.

MaGe Linux Operations
MaGe Linux Operations
MaGe Linux Operations
Master MongoDB: Essential CRUD, Queries, Tools, and User Management Guide

MongoDB Introduction

MongoDB supports CRUD operations (Create, Read, Update, Delete) on documents, provides atomic operations on a single document, does not require a predefined schema, and offers its own rich query language. Each document has a unique _id field that MongoDB generates if omitted.

Display Commands

Help                // Show help
db.help()           // Database methods help
show dbs            // List all databases
use <dbName>        // Switch to a database
show collections    // List collections in current DB
show users          // List users
show roles          // List roles
show profile        // Show recent operations >1ms
load('file.js')     // Execute a JavaScript file

CRUD Basics

Insert Documents

# Single insert
use dba
db.test.insert({"name":"zhangya","age":27,"ad":"北京市朝阳区"})
# Multiple insert
db.inventory.insertMany([
  {"item":"journal","qty":25,"size":{"h":14,"w":21,"uom":"cm"},"status":"A"},
  {"item":"notebook","qty":50,"size":{"h":8.5,"w":11,"uom":"in"},"status":"A"},
  {"item":"paper","qty":100,"size":{"h":8.5,"w":11,"uom":"in"},"status":"D"},
  {"item":"planner","qty":75,"size":{"h":22.85,"w":30,"uom":"cm"},"status":"D"},
  {"item":"postcard","qty":45,"size":{"h":10,"w":15.25,"uom":"cm"},"status":"A"}
])

Read Documents

# Find one document
db.inventory.findOne()
# Find all documents
db.inventory.find()
# Query by condition
db.inventory.find({"status":"A"})
# Projection and pretty output
db.inventory.find({"uid":999}).pretty()

Conditional Queries

# Equality
db.inventory.find({"status":"D"})
# Field query
db.inventory.find({"size.uom":"cm"})
# AND condition
db.inventory.find({"size.h":{$gt:10},"status":"D"})
# OR condition
db.inventory.find({$or:[{"qty":{$lt:50}},{"size.uom":"in"}]})
# Regex
db.inventory.find({"status":"A","item":/^p/})

Update Documents

# Update one document
db.inventory.updateOne(
  {"item":"paper"},
  {$set:{"size.uom":"cm","status":"P"},$currentDate:{"lastModified":true}}
)
# Update many documents
db.inventory.updateMany(
  {"qty":{$lt:50}},
  {$set:{"size.uom":"cm","status":"P"},$currentDate:{"lastModified":true}}
)

Delete Documents

# Delete one document
db.inventory.deleteOne({"status":"D"})
# Delete many documents
db.inventory.deleteMany({"status":"P"})

MongoDB Tools

Official documentation: https://docs.mongodb.com/manual/reference/program/

mongod : Main daemon that handles data requests and background management.

mongos : Router for sharded clusters, directs queries to appropriate shards.

mongostat : Provides real‑time statistics of running mongod/mongos instances.

mongotop : Shows time spent reading/writing data per collection.

mongooplog : Polls remote oplog for real‑time migration.

mongoperf : Benchmarks disk I/O performance.

Authentication and Authorization

MongoDB uses role‑based access control. Create the first admin user with db.createUser() and assign roles such as root, readWrite, dbAdmin, etc. Example:

use admin
db.createUser({user:"admin",pwd:"123456",roles:[{role:"root",db:"admin"}]})

Other roles include read, readWriteAnyDatabase, userAdmin, and more. Users are stored in the admin.system.users collection.

Configuration File

# Enable role‑based access control
security:
  authorization: enabled

User Management Examples

Create a database‑specific admin:

use pincheng
db.createUser({user:"pcadmin",pwd:"123",roles:[{role:"dbAdmin",db:"pincheng"}]})

Create a read‑write user for the same database:

use pincheng
db.createUser({user:"user",pwd:"user",roles:[{role:"readWrite",db:"pincheng"}]})

Create a user with different roles on multiple databases:

use test
db.createUser({user:"myTester",pwd:"xyz123",roles:[{role:"readWrite",db:"test"},{role:"read",db:"test2"}]})

View users:

use admin
db.system.users.find().pretty()

Delete users (requires root):

use pincheng
db.dropUser("pcadmin")
use admin
db.dropUser("myTester")
Original source: https://pincheng.xyz/forward/73b3481b.html (Author: BingCheng)
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.

AuthenticationCRUDMongoDBNoSQL
MaGe Linux Operations
Written by

MaGe Linux Operations

Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.

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.