Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> MongoDB

MongoDB: $match ใน Aggregation Pipeline ทำงานได้จริง

$match ใน aggregation pipeline ทำงานได้อย่างสมบูรณ์ ใช้กรองเอกสารก่อนเข้าสู่ stage ถัดไป สร้างคอลเลกชันตัวอย่าง:

> db.demo358.insertOne({"ClientId":101,"ClientName":"Chris","ClientAge":34});
{ "acknowledged" : true, "insertedId" : ObjectId("5e5692c0f8647eb59e5620cb") }
> db.demo358.insertOne({"ClientId":102,"ClientName":"David","ClientAge":32});
{ "acknowledged" : true, "insertedId" : ObjectId("5e5692caf8647eb59e5620cc") }
> db.demo358.insertOne({"ClientId":103,"ClientName":"David","ClientAge":35});
{ "acknowledged" : true, "insertedId" : ObjectId("5e5692d2f8647eb59e5620cd") }
> db.demo358.insertOne({"ClientId":104,"ClientName":"Bob","ClientAge":31});
{ "acknowledged" : true, "insertedId" : ObjectId("5e5692ddf8647eb59e5620ce") }
> db.demo358.insertOne({"ClientId":105,"ClientName":"Chris","ClientAge":36});
{ "acknowledged" : true, "insertedId" : ObjectId("5e5692e7f8647eb59e5620cf") }

แสดงข้อมูล:

> db.demo358.find();

คิวรี aggregation ใช้ $match กรองชื่อ David แล้ว $count นับจำนวน:

> db.demo358.aggregate([
  { $match : { "ClientName" : "David" }},
  { "$count": "ClientName" }
]);

ผลลัพธ์ (เจอ 2 รายการ):

{ "ClientName" : 2 }

ข้อสำคัญของ $match ใน Aggregation

  • วาง $match เป็น stage แรก เพื่อใช้ index ได้ (performance สำคัญ)
  • Syntax เหมือน find() query ทุกประการ
  • ไม่สามารถใช้ aggregation operators ($add, $cond, etc.) ได้ใน $match
  • $count: นับจำนวนเอกสารที่เหลือ คืนค่าเป็นฟิลด์ที่ระบุ

ตัวอย่างเพิ่มเติม

db.collection.aggregate([
  { $match: { status: "active", age: { $gte: 18 } } },
  { $group: { _id: "$department", count: { $sum: 1 } } }
])