Giới thiệu
Để truy vấn collection (table) trong MongoDB qua dòng lệnh (mongo shell), bạn sử dụng cú pháp db.tenCollection.find() sau khi đã chọn database.
Các bước kết nối và truy vấn
1. Chuyển sang database mong muốn
> use sample;
switched to db sample
> db;
sample
2. Xem danh sách collection
> show collections;
Kết quả ví dụ:
arraySizeErrorDemo
basicInformationDemo
copyThisCollectionToSampleDatabaseDemo
deleteAllRecordsDemo
deleteDocuments
deleteDocumentsDemo
deleteSomeInformation
documentWithAParticularFieldValueDemo
employee
findListOfIdsDemo
findSubstring
getAllRecordsFromSourceCollectionDemo
getElementWithMaxIdDemo
internalArraySizeDemo
largestDocumentDemo
makingStudentInformationClone
oppositeAddToSetDemo
prettyDemo
returnOnlyUniqueValuesDemo
selectWhereInDemo
sourceCollection
studentInformation
sumOfValueDemo
sumTwoFieldsDemo
truncateDemo
updateInformation
userInformation
3. Truy vấn collection (ví dụ: userInformation)
> db.userInformation.find();
4. Kết quả
{ "_id" : ObjectId("5c6a765964f3d70fcc9147f5"), "Name" : "John", "Age" : 30, "isStudent" : false, "Subjects" : [ "Introduction to java", "Introduction to MongoDB" ] }
Các lệnh hữu ích khác trong mongo shell
| Lệnh | Chức năng |
|---|---|
show dbs | Hiển thị tất cả database |
use <dbname> | Chuyển database |
show collections | Hiển thị collection trong DB hiện tại |
db.<collection>.find() | Truy vấn tất cả document |
db.<collection>.find().pretty() | Truy vấn và format đẹp |
db.<collection>.findOne() | Lấy 1 document đầu tiên |
db.<collection>.countDocuments() | Đếm số document |
Kết nối từ terminal (không vào shell)
# Thực hiện query trực tiếp từ bash/cmd
mongo sample --eval "db.userInformation.find().forEach(printjson)"
# Hoặc với file script
mongo sample script.js
Lưu ý
- MongoDB không có khái niệm "table" - gọi là collection
- Collection được tạo tự động khi insert document đầu tiên
- Tên collection phân biệt chữ hoa/thường