Để chọn một trường đơn lẻ, dùng projection trong find(). Cú pháp:
db.yourCollectionName.find({"yourFieldName":yourValue},{"yourSingleFieldName":1,_id:0});
"yourSingleFieldName":1, _id:0 nghĩa là chỉ lấy trường đó, loại bỏ _id.
Tạo collection singleFieldDemo:
> db.singleFieldDemo.insertOne({"StudentName":"David","StudentAge":28});
{ "acknowledged" : true, "insertedId" : ObjectId("5c6eba356fd07954a489067c") }
... (thêm Bob 18, Chris 24, Robert 26) ...
Hiển thị tất cả:
> db.singleFieldDemo.find().pretty();
Chỉ lấy StudentName nơi StudentAge = 18:
> db.singleFieldDemo.find({"StudentAge":18},{"StudentName":1,"_id":0});
Kết quả:
{ "StudentName" : "Bob" }