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

การข้ามค่า null ในเอกสาร MongoDB

ใช้ $ne: null ใน Aggregate

เพื่อกรองเอกสารที่ไม่มีค่า null ให้ใช้ "$ne" : null ในขั้นตอน $match หลังจาก $unwind

สร้างข้อมูลตัวอย่าง

> db.demo722.insertOne({
    id:101,
    details: [
        { Name:""},
        { Name: "David"},
        {Name:null},
        {Name:"Carol"}
    ]
});

แสดงข้อมูลทั้งหมด

> db.demo722.find();

ผลลัพธ์:

{ "_id" : ObjectId("5eab07d543417811278f5889"), "id" : 101, "details" : [ { "Name" : "" }, { "Name" : "David" }, { "Name" : null }, { "Name" : "Carol" } ] }

คิวรีข้ามค่า null

> db.demo722.aggregate([
    {"$unwind": "$details"},
    {"$match": { "details.Name" :{ "$ne" : null } } }
])

ผลลัพธ์: ไม่รวมเอกสารที่ Name เป็น null

{ "_id" : ObjectId("5eab07d543417811278f5889"), "id" : 101, "details" : { "Name" : "" } }
{ "_id" : ObjectId("5eab07d543417811278f5889"), "id" : 101, "details" : { "Name" : "David" } }
{ "_id" : ObjectId("5eab07d543417811278f5889"), "id" : 101, "details" : { "Name" : "Carol" } }

หมายเหตุ: ค่าว่าง ("") ยังคงรวมอยู่ เพราะไม่ใช่ null