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

ใช้ $cond ใน MongoDB Projection ตรวจสอบความมี/ไม่มีของฟิลด์

สามารถใช้ $cond ร่วมกับ $anyElementTrue เพื่อสร้างฟิลด์ใหม่ที่แสดงสถานะความมีหรือไม่มีของฟิลด์ ค่า NULL (ไม่มีฟิลด์) จะให้ FALSE และอาร์เรย์ว่างก็ให้ FALSE ด้วย $anyElementTrue

สร้างคอลเลกชันพร้อมเอกสาร (บางรายการ StudentName เป็น null บางรายการมีค่า):

> db.presenceDemo.insertOne({"StudentName":null}); 
{ "acknowledged" : true, "insertedId" : ObjectId("5e06f70c25ddae1f53b621f3") } 
> db.presenceDemo.insertOne({"StudentName":"Chris"}); 
{ "acknowledged" : true, "insertedId" : ObjectId("5e06f71425ddae1f53b621f4") } 
> db.presenceDemo.insertOne({"StudentName":null}); 
{ "acknowledged" : true, "insertedId" : ObjectId("5e06f71825ddae1f53b621f5") } 
> db.presenceDemo.insertOne({"StudentName":"David"}); 
{ "acknowledged" : true, "insertedId" : ObjectId("5e06f71e25ddae1f53b621f6") }

แสดงเอกสารทั้งหมด:

> db.presenceDemo.find();

ผลลัพธ์:

คำสั่ง Aggregation ใช้ $project พร้อม $cond และ $anyElementTrue ตรวจสอบ StudentName:

> db.presenceDemo.aggregate([ 
...     { "$project": { 
...         "MyValue": { 
...             "$cond": [ 
...                 { "$anyElementTrue": [ [ "$StudentName" ] ] }, 
...                 1, 
...                 0 
...             ] 
...         } 
...     }} 
... ]);

ผลลัพธ์ - MyValue = 1 ถ้ามีค่า, 0 ถ้าเป็น null: