ใช้ Projection (พารามิเตอร์ที่ 2 ของ find()) ระบุฟิลด์ที่ต้องการคืนค่า ร่วมกับ $and ใน Query เพื่อกรองเอกสารหลายเงื่อนไข
สร้างคอลเลกชันและข้อมูลตัวอย่าง
> 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") }
แสดงข้อมูลทั้งหมด
> db.selectingASingleFieldDemo.find().pretty();
ผลลัพธ์: 4 เอกสาร
Query: หา คนอายุ > 21 และ ประเทศ = AUS → คืนเฉพาะ StudentFirstName
> db.selectingASingleFieldDemo.find(
{$and: [
{StudentAge: {$gt: 21}},
{"StudentCountryName": "AUS"}
]},
{StudentFirstName: 1, _id: 0}
);
ผลลัพธ์: David และ Robert (อายุ 24, 26 ประเทศ AUS)
{"StudentFirstName": "David"}
{"StudentFirstName": "Robert"}
การทำงาน
$andรวมเงื่อนไข 2 อย่าง: Age > 21 และ Country = AUS- Projection
{StudentFirstName: 1, _id: 0}คืนเฉพาะชื่อ (ซ่อน _id) - John (US) และ Carol (Age 21, UK) ไม่ตรงเงื่อนไข
Projection Rules
1= Include,0= Exclude- ไม่ผสม Include/Exclude ได้ (ยกเว้น
_id: 0) _idคืนค่า Default ต้องระบุ_id: 0ถ้าไม่ต้องการ
$and แบบ Implicit (ไม่ต้องเขียน $and)
เมื่อไหร่ต้องใช้ $and โดยชัดเจน (Explicit)
- เงื่อนไขซ้ำฟิลด์เดียวกัน:
{$and: [{age: {$gte: 18}}, {age: {$lte: 65}}]} - รวมกับ $or/$nor ใน Logic ซับซ้อน
- Generated Query จากโปรแกรม (Programmatic Query Building)