Sử dụng **Projection** (tham số thứ 2 của find()) để chỉ lấy giá trị của field cần thiết, giảm băng thông và bộ nhớ.
Cú pháp
db.collection.find({ }, { "tênTrường": 1, _id: 0 }).pretty();
1: Include (lấy field này).0: Exclude (loại bỏ field này)._idmặc định là 1, phải tắt rõ ràng nếu không muốn.- Không thể mix include/exclude (trừ _id).
Ví dụ minh họa
Tạo collection retrieveValueFromAKeyDemo:
> db.retrieveValueFromAKeyDemo.insertOne({ "CustomerName": "Larry", "CustomerAge": 21, "CustomerCountryName": "US" });
> db.retrieveValueFromAKeyDemo.insertOne({ "CustomerName": "Chris", "CustomerAge": 24, "CustomerCountryName": "AUS" });
> db.retrieveValueFromAKeyDemo.insertOne({ "CustomerName": "Mike", "CustomerAge": 26, "CustomerCountryName": "UK" });
Hiển thị tất cả:
> db.retrieveValueFromAKeyDemo.find().pretty();
Kết quả:
{ "_id" : ..., "CustomerName" : "Larry", "CustomerAge" : 21, "CustomerCountryName" : "US" }
{ "_id" : ..., "CustomerName" : "Chris", "CustomerAge" : 24, "CustomerCountryName" : "AUS" }
{ "_id" : ..., "CustomerName" : "Mike", "CustomerAge" : 26, "CustomerCountryName" : "UK" }
Chỉ lấy CustomerCountryName (và ẩn _id)
> db.retrieveValueFromAKeyDemo.find({}, { "CustomerCountryName": 1, _id: 0 }).pretty();
Kết quả:
{ "CustomerCountryName" : "US" }
{ "CustomerCountryName" : "AUS" }
{ "CustomerCountryName" : "UK" }
Các biến thể
- Giữ _id:
{ "CustomerCountryName": 1 }(mặc định _id: 1). - Lấy nhiều field:
{ "CustomerName": 1, "CustomerAge": 1, _id: 0 }. - Loại bỏ field (Exclude):
{ "CustomerAge": 0 }(lấy tất cả TRỪ CustomerAge). Không mix với include. - Sub-field (Dot notation):
{ "address.city": 1, _id: 0 }. - Array element (Positional $):
{ "arr.$": 1 }trong findOne sau khi match.
Trong Aggregation: $project
db.collection.aggregate([
{ $project: { _id: 0, CustomerCountryName: 1 } }
]);
Lợi ích
- Giảm network traffic (chỉ truyền dữ liệu cần thiết).
- Tăng tốc độ query (ít dữ liệu đọc từ disk/memory).
- Bảo mật: Không lộ field nhạy cảm (password hash, token...).