Để chỉ chọn (project) các trường cần thiết và ẩn các trường không cần trong kết quả truy vấn MongoDB, bạn sử dụng tham số **projection** (tham số thứ 2) của find(). Đặt giá trị 1 để hiển thị, 0 để ẩn. _id mặc định là 1, phải tắt rõ ràng nếu không muốn.
1. Tạo bộ sưu tập
> db.demo415.insertOne({ "ClientName": "Robert", "ClientCountryName": "US" });
> db.demo415.insertOne({ "ClientName": "David", "ClientCountryName": "UK" });
> db.demo415.insertOne({ "ClientName": "Bob", "ClientCountryName": "AUS" });
2. Xem toàn bộ trường
> db.demo415.find();
Kết quả: _id, ClientName, ClientCountryName.
3. Chỉ hiển thị ClientCountryName (ẩn _id và ClientName)
> db.demo415.find({}, { _id: 0, ClientName: 0 });
4. Kết quả
{ "ClientCountryName": "US" }
{ "ClientCountryName": "UK" }
{ "ClientCountryName": "AUS" }
Quy tắc Projection:
- Không thể trộn
1và0(trừ_id: 0). - Đúng:
{ a: 1, b: 1 }(chỉ lấy a,b) HOẶC{ a: 0, b: 0, _id: 0 }(loại a,b,_id). - Sai:
{ a: 1, b: 0 }(trộn include/exclude).
Projection trong Aggregation ($project): Mạnh hơn, cho phép tính toán, đổi tên, restructure.
db.demo415.aggregate([{ $project: { _id: 0, Country: "$ClientCountryName" } }]);
Lợi ích: Giảm network transfer, giảm memory client, tăng tốc độ (covered query nếu index đủ).