Sử dụng projection (trường thứ 2 của find()) để chỉ lấy trường cần thiết.
Tạo collection
> db.selectingASingleFieldDemo.insertOne({"StudentFirstName": "John", "StudentAge": 23, "StudentCountryName": "US"});
{ "acknowledged": true, "insertedId": ObjectId("5cd547142cba06f46efe9f02") }
> db.selectingASingleFieldDemo.insertOne({"StudentFirstName": "Carol", "StudentAge": 21, "StudentCountryName": "UK"});
{ "acknowledged": true, "insertedId": ObjectId("5cd5471f2cba06f46efe9f03") }
> db.selectingASingleFieldDemo.insertOne({"StudentFirstName": "David", "StudentAge": 24, "StudentCountryName": "AUS"});
{ "acknowledged": true, "insertedId": ObjectId("5cd5472c2cba06f46efe9f04") }
> db.selectingASingleFieldDemo.insertOne({"StudentFirstName": "Robert", "StudentAge": 26, "StudentCountryName": "AUS"});
{ "acknowledged": true, "insertedId": ObjectId("5cd548382cba06f46efe9f05") }
Hiển thị tất cả
> db.selectingASingleFieldDemo.find().pretty();
Truy vấn: Age > 21 VÀ Country = "AUS", chỉ trả về StudentFirstName
> db.selectingASingleFieldDemo.find(
{ $and: [{ StudentAge: { $gt: 21 } }, { "StudentCountryName": "AUS" }] },
{ StudentFirstName: 1, _id: 0 }
);
Kết quả (chỉ tên, không _id):
{ "StudentFirstName": "David" }
{ "StudentFirstName": "Robert" }
Giải thích: $and kết hợp hai điều kiện. Projection { StudentFirstName: 1, _id: 0 } chỉ bao gồm StudentFirstName, loại trừ _id (mặc định luôn có trừ khi tắt).