Master MongoDB: From Basics to Advanced Operations
This comprehensive guide walks you through MongoDB fundamentals, installation checks, service management, user authentication, database and collection creation, and essential CRUD commands, providing clear examples and code snippets to help you efficiently manage and query your NoSQL data.
MongoDB Introduction
MongoDB is an open‑source document‑oriented NoSQL database that stores data in flexible BSON format, using collections of documents instead of tables, and supports aggregation pipelines, geospatial queries, and more.
Key Features
Document storage with flexible schema
High performance and horizontal scaling
Built‑in high availability via replica sets and sharding
Dynamic queries and aggregation
Easy adaptability to changing requirements
Scalable to billions of records
Open‑source community and enterprise editions
Initial Connection and Service Checks
Check MongoDB Service Status
[root@jeven ~]# systemctl status mongod
● mongod.service - MongoDB Database Server
Loaded: loaded (/usr/lib/systemd/system/mongod.service; enabled; vendor preset: disabled)
Active: active (running) since Fri 2023-09-15 00:01:03 CST; 31s ago
Docs: https://docs.mongodb.org/manual
Main PID: 23735 (mongod)
CGroup: /system.slice/mongod.service
└─23735 /usr/bin/mongod -f /etc/mongod.confCheck MongoDB Version
[root@jeven ~]# mongo --version
MongoDB shell version v5.0.21
Build Info: {
"version": "5.0.21",
"gitVersion": "4fad44a858d8ee2d642566fc8872ef410f6534e4",
"openSSLVersion": "OpenSSL 1.0.1e-fips 11 Feb 2013",
"allocator": "tcmalloc",
"environment": {
"distmod": "rhel70",
"distarch": "x86_64",
"target_arch": "x86_64"
}
}Local Connection
mongoExit MongoDB
quit()Service Operations
Start MongoDB: systemctl start mongod Enable autostart: systemctl enable mongod Disable autostart: systemctl disable mongod Stop MongoDB:
systemctl stop mongodDatabase Environment Checks
Query Version Inside Shell
> db.version()
5.0.21Check Server Status
> db.serverStatus()
{ "ok" : 0, "errmsg" : "not authorized on admin to execute command { serverStatus: 1.0 }", "code" : 13, "codeName" : "Unauthorized" }Check Build Info
db.serverBuildInfo()User Management
User Roles Overview
Database user roles: read, readWrite; Database admin roles: dbAdmin, dbOwner, userAdmin; Cluster admin roles: clusterAdmin, clusterManager, clusterMonitor, hostManager; Backup/restore roles: backup, restore; Global roles: readAnyDatabase, readWriteAnyDatabase, userAdminAnyDatabase, dbAdminAnyDatabase; Superuser role: root; Internal role: __system.
Create Admin User
use admin;
db.createUser({
user: "admin",
pwd: "admin",
roles: [{role: "userAdminAnyDatabase", db: "admin"}]
})Enable Authentication
security:
authorization: enabledAuthenticate After Restart
use admin
db.auth("admin","admin")
1Create Root User
db.createUser({
user: "root",
pwd: "root",
roles: ["root"]
})Create Normal User
use admin;
db.createUser({
user: "jeven",
pwd: "jeven",
roles: [{role: "readWrite", db: "test"}]
})Query Users
show users; db.system.users.find().pretty()Delete User
use admin;
db.auth("admin","admin");
db.dropUser("jeven")Change User Password
use admin
db.changeUserPassword("jeven","aa123")Database and Collection Operations
Create Database
use huawei;
switched to db huaweiShow Databases
show dbsInsert a document to make the new database appear:
db.huawei.insertOne({"name":"mall"})Create Collection
db.createCollection("class")View Collections
show tablesDrop Collection
db.huawei.drop()Delete Database
use huawei;
db.dropDatabase();Data Operations
Insert Documents
db.class.insert({ "name":"natasha", "age":"18", "genden":"female" });
db.class.insert({ "type":"phone", "price":"3999", "xinghao":"huawei", "desc":"xxx" });Update Document
db.class.update({"type":"phone"},{ $set:{ "type":"televison" }})Replace Document
db.class.save({
"_id": ObjectId("6503466fc15bb4f0c6168128"),
"title":"MongoDB",
"description":"MongoDB 是一个 Nosql 数据库",
"by":"Runoob",
"url":"http://www.aa.com",
"tags":["mongodb","NoSQL"],
"likes":110
})Query Documents
Find all: db.class.find() Find with condition: db.class.find({"type":"televison"}) Pretty print:
db.class.find().pretty()Delete Collection
db.runoob.drop()Delete Document
db.class.remove({"type":"televison"})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.
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.
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.
