Database Command trong MongoDB
- 10-03-2026
- Toanngo92
- 0 Comments
Trong session này, chúng ta sẽ thảo luận một số vấn đề:
- Giải thích tầm quan trọng của database commands trong MongoDB
- Mô tả các loại database commands khác nhau kèm ví dụ
Các lệnh database chủ yếu liên quan đến:
- tạo và chỉnh sửa dữ liệu của user và collection
- xác thực người dùng
- nhóm nhiều document
Các truy vấn sử dụng database commands thường khá phức tạp.
Session này sẽ:
- giải thích các loại database commands
- mô tả các tham số của từng command
- hướng dẫn cách sử dụng với ví dụ
Mục lục
5.1 Introduction to Database Commands
Các developer sử dụng MongoDB database commands để:
- tạo database
- chỉnh sửa database
- cập nhật database
Một số nhóm lệnh database trong MongoDB gồm:
MongoDB Database Commands
User Management
- createUser
- grantRolesToUser
- usersInfo
- dropUser
Authentication
- auth
- getnonce
Write Operation
- insert
- find
- findAndModify
- update
- delete
Aggregation
- count
- aggregate
- distinct
Trước khi tìm hiểu các nhóm lệnh này, ta cần hiểu cách chạy một command.
Cú pháp:
db.runCommand({ <command> })
Ở đây:
- người dùng cung cấp command cần thực thi
- command có thể ở dạng document hoặc string
Mặc dù db.runCommand chạy command trên database hiện tại, một số command chỉ áp dụng cho admin database.
Do đó người dùng phải:
- chuyển sang database admin
- hoặc dùng
db.adminCommand
Cú pháp:
db.adminCommand({ <command> })
Lệnh runCommand cung cấp một helper để chạy các database command.
Phương thức này tạo ra giao diện thống nhất giữa MongoDB shell và driver, vì vậy đây là cách được ưu tiên sử dụng để gọi database command.
Các lệnh db.runCommand và db.adminCommand nhận database command làm tham số, có thể là:
- document
- string
Nếu command được truyền dưới dạng string, MongoDB sẽ tự động chuyển thành document.
5.2 User Management Commands
Các lệnh quản lý người dùng trong MongoDB cho phép thực hiện các thao tác như:
- tạo user
- xóa user
- xem thông tin user
- gán role cho user
MongoDB Database Commands
| Command | Chức năng |
|---|---|
| createUser | Tạo user |
| grantRolesToUser | Gán role cho user |
| usersInfo | Xem thông tin user |
| dropUser | Xóa user |
5.2.1 createUser Command
Người dùng có thể sử dụng lệnh createUser để tạo user mới trong database đang hoạt động.
Nếu user đã tồn tại, MongoDB sẽ trả về lỗi duplicate user.
Cú pháp
db.runCommand({
createUser: "<name>",
pwd: passwordPrompt() // hoặc "<cleartext password>",
customData: { <any information> },
roles: [
{ role: "<role>", db: "<database>" } | "<role>"
],
writeConcern: { <write concern> },
authenticationRestrictions: [
{
clientSource: ["<IP|CIDR range>", ...],
serverAddress: ["<IP|CIDR range>", ...]
}
],
mechanisms: ["<scram-mechanism>", ...],
digestPassword: <boolean>,
comment: <any>
})
Bảng 5.1: Các tham số của createUser
| Parameter | Type | Description |
|---|---|---|
| createUser | string | Tên user mới |
| pwd | string | Password của user |
| customData | document | Thông tin bổ sung cho user |
| roles | array | Role được gán cho user |
| digestPassword | boolean | Xác định password được digest ở client hay server |
| writeConcern | document | Mức độ write concern cho thao tác tạo user |
| authenticationRestrictions | array | Danh sách IP được phép đăng nhập |
| mechanism | array | Cơ chế xác thực SCRAM |
Ví dụ
Tạo user User_1 trong database sample_training với role readWrite.
use sample_training
db.runCommand({
createUser: "User_1",
pwd: passwordPrompt(),
roles: ["readWrite"]
})
Hệ thống sẽ yêu cầu nhập password.
Ví dụ:
Enter password
********
{ ok: 1 }
Tạo user thứ hai
db.runCommand({
createUser: "User_2",
pwd: passwordPrompt(),
roles: ["readWrite"]
})
Kết quả:
Enter password
********
{ ok: 1 }
5.2.2 grantRolesToUser Command
Lệnh grantRolesToUser dùng để gán thêm role cho user.
Cú pháp
db.runCommand({
grantRolesToUser: "<user>",
roles: [ <roles> ],
writeConcern: { <write concern> },
comment: <any>
})
Gán role cho user
Khi gán role cho user trong database hiện tại:
- chỉ cần ghi tên role
Ví dụ:
readWrite
Hoặc có thể chỉ định role dạng document:
{ role: "<role>", db: "<database>" }
Nếu role thuộc database khác, bắt buộc phải dùng dạng document.
Ví dụ
Database sample_supplies
Gán role read của database sample_supplies cho User_1 trong database sample_training.
db.runCommand({
grantRolesToUser: "User_1",
roles: [
{ role: "read", db: "sample_supplies" },
"readWrite"
]
})
Dưới đây là bản dịch đầy đủ phần tiếp theo của Session 5 theo đúng nội dung trong ảnh bạn gửi.
Hình 5.3: Chỉ định thêm quyền read cho User_1
Một quyền read bổ sung trong một database khác đã được gán cho User_1.
5.2.3 Lệnh usersInfo
Lệnh usersInfo trả về thông tin của một hoặc nhiều người dùng trong database.
Cú pháp
db.runCommand({
usersInfo: <various>,
showCredentials: <Boolean>,
showCustomData: <Boolean>,
showPrivileges: <Boolean>,
showAuthenticationRestrictions: <Boolean>,
filter: <document>,
comment: <any>
})
Bảng 5.2: Các dạng của lệnh usersInfo
| Form | Description |
|---|---|
{ usersInfo: 1 } | Trả về thông tin của tất cả người dùng trong database hiện tại |
{ usersInfo: <username> } | Trả về thông tin của một user cụ thể |
{ usersInfo: { user: <name>, db: <db> } } | Trả về thông tin user trong database được chỉ định |
{ usersInfo: [ { user: <name>, db: <db> }, ... ] } | Trả về thông tin nhiều user |
{ forAllDBs: true } | Trả về thông tin user trong tất cả database |
Ví dụ
Xem thông tin của User_1 trong database sample_training
db.runCommand({
usersInfo: { user: "User_1", db: "sample_training" },
showPrivileges: true
})
Hình 5.4: Thông tin của User_1 trong database sample_training
Kết quả hiển thị:
- user id
- username
- database
- authentication mechanisms
- roles
- inherited roles
- privileges
5.2.4 Lệnh dropUser
Lệnh dropUser dùng để xóa một user khỏi database hiện tại.
Cú pháp
db.runCommand({
dropUser: "<user>",
writeConcern: { <write concern> },
comment: <any>
})
Ví dụ
Xóa User_2 khỏi database sample_training
db.runCommand({ dropUser: "User_2" })
Hình 5.5: Xóa User_2 khỏi database sample_training
Kết quả:
{ ok: 1 }
Điều này cho biết user đã được xóa thành công.
5.3 Authentication Commands
Authentication là quá trình xác thực thông tin đăng nhập của người dùng dựa trên các giá trị được lưu trữ.
MongoDB cung cấp bảo mật thông qua các lệnh authentication sau:
MongoDB Authentication Commands
| Command | Description |
|---|---|
| auth | Bắt đầu phiên xác thực bằng username và password |
| getnonce | Tạo mật khẩu dùng một lần (internal command) |
Session này chỉ giải thích auth command, vì getnonce là lệnh nội bộ của MongoDB.
5.3.1 Lệnh Authenticate (db.auth)
Lệnh db.auth xác thực người dùng bằng cơ chế x.509 authentication.
Lệnh này trả về:
- 0 nếu xác thực thất bại
- 1 nếu xác thực thành công
Cú pháp
db.auth({
user: <username>,
pwd: passwordPrompt(), // hoặc "cleartext password"
mechanism: <authentication mechanism>,
digestPassword: <boolean>
})
Bảng 5.3: Tham số của lệnh db.auth
| Parameter | Type | Optional/Mandatory | Description |
|---|---|---|---|
| user | string | Mandatory | Tên người dùng |
| pwd | string | Mandatory | Mật khẩu của user |
| mechanism | string | Optional | Cơ chế authentication |
| digestPassword | boolean | Optional | Xác định có hash password trước khi xác thực hay không |
Nhập mật khẩu khi xác thực
Có 2 cách nhập password
Cách 1
Không nhập password trực tiếp:
db.auth(<username>)
hoặc
db.auth(<username>, passwordPrompt())
MongoDB sẽ yêu cầu nhập password từ bàn phím.
Cách 2
Nhập password trực tiếp:
db.auth(<username>, <password>)
⚠️ Lưu ý
MongoDB chỉ có thể xác thực user sau khi kết nối shell được thiết lập.
Ví dụ
Xác thực user User_1 với password user1 trong database sample_training
db.auth("User_1", "user1")
Kết quả:
{ ok: 1 }
Điều này cho thấy xác thực thành công.
Dưới đây là bản dịch tiếp theo phần 5.4 Write Operation Commands theo đúng nội dung các trang bạn gửi.
5.4 Write Operation Commands
Write operation là thao tác dùng để tạo hoặc chỉnh sửa dữ liệu trong MongoDB.
Trong MongoDB:
- write operations hoạt động trên một collection
- có thể ảnh hưởng đến một hoặc nhiều document trong collection đó.
Các command MongoDB cung cấp cho write operations gồm:
MongoDB Database Commands – Write Operation
| Command | Chức năng |
|---|---|
| insert | Chèn một hoặc nhiều document |
| find | Lấy document từ collection |
| findAndModify | Lấy và chỉnh sửa một document |
| update | Cập nhật một hoặc nhiều document |
| delete | Xóa một hoặc nhiều document |
5.4.1 Insert Command
Lệnh insert dùng để chèn một hoặc nhiều document vào collection.
Lệnh này trả về một document chứa trạng thái của tất cả các thao tác insert.
Cú pháp
db.runCommand({
insert: <collection>,
documents: [ <document>, <document>, ... ],
ordered: <boolean>,
writeConcern: { <write concern> },
bypassDocumentValidation: <boolean>,
comment: <any>
})
Bảng 5.4: Tham số của insert command
| Parameter | Type | Description |
|---|---|---|
| insert | string | Tên collection |
| documents | array | Danh sách document cần insert |
| ordered | boolean | Nếu true, khi một insert lỗi thì các insert còn lại không chạy. Nếu false thì các insert còn lại vẫn tiếp tục |
| writeConcern | document | Mức độ đảm bảo ghi dữ liệu |
| bypassDocumentValidation | boolean | Cho phép insert document không thỏa validation rule |
| comment | any | Chuỗi mô tả để tracking operation trong profiler hoặc logs |
Ví dụ
Trong database sample_analytics, collection accounts.
Insert một document:
- account_id = 988877
- limit = 2000
- products = InvestmentFund
db.runCommand({
insert: "accounts",
documents: [
{
account_id: 988877,
limit: 2000,
products: ["InvestmentFund"]
}
]
})
Kết quả
{ n: 1, ok: 1 }
Điều này cho biết 1 document đã được insert thành công.
Kiểm tra document vừa insert
db.accounts.find({ "account_id": 988877 })
Kết quả
{
_id: ObjectId(...),
account_id: 988877,
limit: 2000,
products: ["InvestmentFund"]
}
5.4.2 Find Command
Lệnh find dùng để:
- chọn các document
- thỏa điều kiện query
- từ một collection
Kết quả trả về là cursor.
Cursor là gì?
Cursor là con trỏ trỏ đến tập kết quả của query.
Người dùng có thể:
- duyệt từng document
- thực hiện thao tác trên tập kết quả
Lưu ý:
- cursor tự động timeout sau 10 phút không hoạt động
- cursor trong session sẽ đóng khi session kết thúc.
Cú pháp find command
db.runCommand({
find: <string>,
filter: <document>,
sort: <document>,
projection: <document>,
hint: <document or string>,
skip: <int>,
limit: <int>,
batchSize: <int>,
singleBatch: <bool>,
comment: <any>,
maxTimeMS: <int>,
readConcern: <document>,
max: <document>,
min: <document>,
returnKey: <bool>,
showRecordId: <bool>,
tailable: <bool>,
oplogReplay: <bool>,
noCursorTimeout: <bool>,
awaitData: <bool>,
allowPartialResults: <bool>,
collation: <document>,
allowDiskUse: <bool>,
let: <document> // MongoDB 5.0
})
| Parameter | Type | Description |
|---|---|---|
| find | string | Tên collection |
| filter | document | Điều kiện lọc |
| sort | document | Sắp xếp kết quả |
| projection | document | Chỉ định các field cần trả về |
| hint | string | Chỉ định index |
| skip | integer | Bỏ qua số document |
| limit | integer | Giới hạn số document trả về |
| batchSize | integer | Số document trả về trong mỗi batch |
| singleBatch | boolean | Đóng cursor sau batch đầu |
| maxTimeMS | integer | Giới hạn thời gian query |
| readConcern | document | Mức độ đảm bảo đọc dữ liệu |
| max | document | Giới hạn trên của index |
| min | document | Giới hạn dưới của index |
| returnKey | boolean | Chỉ trả về index key |
| showRecordId | boolean | Trả về record id |
| noCursorTimeout | boolean | Không timeout cursor |
| collation | document | Quy tắc so sánh string |
Ví dụ
Trong collection accounts của database sample_analytics.
Người dùng muốn tìm các document có:
limit < 6000
Truy vấn:
db.runCommand({
find: "accounts",
filter: { limit: { $lt: 6000 } }
})

Người dùng muốn:
- chỉ hiển thị account_id và limit
- sắp xếp kết quả theo limit
Truy vấn:
db.runCommand({
find: "accounts",
filter: { limit: { $lt: 6000 } },
projection: { account_id: 1, limit: 1 },
sort: { limit: 1 }
})
Kết quả trả về là cursor chứa các document thỏa điều kiện.
5.4.3 Lệnh findAndModify
Lệnh findAndModify:
- lọc document
- sửa document
- trả về một document duy nhất
Document trả về có thể:
- là document trước khi sửa
- hoặc sau khi sửa
Cú pháp
db.runCommand({
findAndModify: <collection-name>,
query: <document>,
sort: <document>,
remove: <boolean>,
update: <document hoặc aggregation pipeline>,
new: <boolean>,
fields: <document>,
upsert: <boolean>,
bypassDocumentValidation: <boolean>,
writeConcern: <document>,
collation: <document>,
arrayFilters: <array>,
hint: <document|string>,
comment: <any>,
let: <document> // MongoDB 5.0
})
Bảng 5.6: Tham số của lệnh findAndModify
| Parameter | Type | Description |
|---|---|---|
| findAndModify | string | Tên collection |
| query | document | Điều kiện chọn document |
| sort | document | Chỉ định document đầu tiên trong kết quả đã sort |
| remove | boolean | Nếu true → xóa document |
| update | document/array | Nội dung update |
| new | boolean | Nếu true → trả về document sau khi update |
| fields | document | Các field cần trả về |
| writeConcern | document | Mức độ đảm bảo ghi |
| collation | document | Quy tắc so sánh chuỗi |
Lưu ý
Mặc định lệnh này trả về document trước khi sửa.
Nếu muốn trả về document sau khi sửa phải đặt:
new: true
Ví dụ
Từ collection accounts trong database sample_analytics.
Người dùng muốn:
- tìm document có
limit = 2000 - cập nhật thành 2500
- hiển thị document sau khi sửa
Truy vấn:
db.runCommand({
findAndModify: "accounts",
query: { limit: 2000 },
update: { $set: { limit: 2500 } },
new: true
})
Kết quả:
{
account_id: 988877,
limit: 2500,
products: ["InvestmentFund"]
}
Lưu ý
Nếu không có document nào khớp điều kiện, giá trị trả về sẽ là:
value: null
5.4.4 Lệnh update
Lệnh update dùng để:
- sửa một hoặc nhiều document trong collection
Một lệnh update có thể chứa:
- một update statement
- hoặc nhiều update statements
Cú pháp
db.runCommand({
update: <collection>,
updates: [
{
q: <query>,
u: <document hoặc pipeline>,
c: <document>, // MongoDB 5.0
upsert: <boolean>,
multi: <boolean>,
collation: <document>,
arrayFilters: <array>,
hint: <document|string>
}
],
ordered: <boolean>,
writeConcern: { <write concern> },
bypassDocumentValidation: <boolean>,
comment: <any>,
let: <document> // MongoDB 5.0
})
| Parameter | Type | Description |
|---|---|---|
| update | string | Tên collection |
| updates | array | Danh sách update statements |
| ordered | boolean | Nếu true → khi lỗi thì các update sau không chạy |
| writeConcern | document | Mức độ đảm bảo ghi |
| bypassDocumentValidation | boolean | Cho phép update document không hợp lệ |
| comment | any | Chuỗi mô tả operation |
| Field | Type | Description |
|---|---|---|
| q | document | Điều kiện query |
| u | document/array | Nội dung update |
Ví dụ
Collection accounts trong database sample_analytics
Một số document có:
limit = 3000
Truy vấn xem các document này:
db.accounts.find({ limit: 3000 })

Cập nhật dữ liệu
Người dùng muốn:
limit = 3000 → 4000
Truy vấn:
db.runCommand({
update: "accounts",
updates: [
{
q: { limit: 3000 },
u: { $inc: { limit: 1000 } },
multi: true
}
]
})
Hình 5.12: Kết quả cập nhật
n: 2
modified: 2
ok: 1
Có 2 document được cập nhật.
Kiểm tra dữ liệu sau khi update
db.accounts.find({ limit: 4000 })
Hình 5.13: Kết quả sau khi cập nhật
Hai document hiện có:
limit = 4000
Bài tập
Phần 1 — Tạo cơ sở dữ liệu và chèn dữ liệu (3 điểm)
Yêu cầu:
Tạo cơ sở dữ liệu:
companyDB
Tạo collection:
employees
Chèn các document sau:
{
employee_id: 1,
name: "An",
age: 25,
department: "Kỹ thuật",
scores: [8, 9, 7],
skills: ["MongoDB", "NodeJS", "Docker"]
}
{
employee_id: 2,
name: "Bình",
age: 27,
department: "Marketing",
scores: [6, 7, 8],
skills: ["SEO", "Content"]
}
{
employee_id: 3,
name: "Chi",
age: 24,
department: "Kỹ thuật",
scores: [9, 9, 10],
skills: ["MongoDB", "Python", "Docker"]
}
{
employee_id: 4,
name: "Dũng",
age: 26,
department: "Nhân sự",
scores: [7, 6, 8],
skills: ["Recruitment", "Training"]
}
{
employee_id: 5,
name: "Hà",
age: 28,
department: "Kỹ thuật",
scores: [8, 8, 9],
skills: ["Python", "Cloud"]
}
Thang điểm:
| Nội dung | Điểm |
|---|---|
| Tạo database và collection đúng | 1 |
| Chèn đúng dữ liệu | 2 |
Phần 2 — Truy vấn dữ liệu cơ bản (4 điểm)
Câu 1 (1 điểm)
Tìm các nhân viên thuộc phòng ban:
"Kỹ thuật"
Câu 2 (1 điểm)
Tìm các nhân viên có tuổi nhỏ hơn 27.
Câu 3 (1 điểm)
Tìm các nhân viên có kỹ năng:
"MongoDB"
Câu 4 (1 điểm)
Chỉ hiển thị các trường sau:
-
name -
department -
skills
Phần 3 — Truy vấn với mảng (4 điểm)
Câu 1 (1.5 điểm)
Tìm các nhân viên có ít nhất một điểm số lớn hơn hoặc bằng 9 trong mảng scores.
Câu 2 (1.5 điểm)
Tìm các nhân viên có ít nhất 3 kỹ năng.
Câu 3 (1 điểm)
Sắp xếp danh sách nhân viên theo tuổi theo thứ tự giảm dần.
Phần 4 — Cập nhật và xóa dữ liệu (3 điểm)
Câu 1 (1.5 điểm)
Thêm kỹ năng:
"Git"
vào nhân viên có:
employee_id = 1
Câu 2 (1.5 điểm)
Xóa nhân viên có:
employee_id = 4
Phần 5 — Aggregation Pipeline (4 điểm)
Yêu cầu:
Thống kê số lượng nhân viên phòng Kỹ thuật theo từng kỹ năng.
Pipeline phải thực hiện các bước sau:
-
Tách mảng
skills -
Lọc các nhân viên có
department = "Kỹ thuật" -
Đếm số lượng nhân viên theo từng kỹ năng
-
Sắp xếp kết quả theo thứ tự giảm dần
-
Hiển thị kết quả theo dạng:
skill
total_employees
Kết quả mẫu:
MongoDB -> 2
Python -> 2
Docker -> 2
Cloud -> 1
NodeJS -> 1
Thang điểm:
| Thành phần | Điểm |
|---|---|
$unwind |
1 |
$match |
0.5 |
$group |
1 |
$sort |
0.5 |
$project |
1 |
| Tổng | 4 |
Phần 6 — Index (1 điểm)
Tạo index cho trường:
department
Phần 7 — Transaction (1 điểm)
Thực hiện transaction với các yêu cầu sau:
-
Tăng tuổi của nhân viên có
employee_id = 1lên 1 -
Tăng tuổi của nhân viên có
employee_id = 2lên 1
Sau đó commit transaction.

