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

การข้ามค่า NULL และ UNDEFINED ในคิวรี่ MongoDB

ใช้ operator $ne (not equal) เพื่อกรองเอกสารที่ฟิลด์ไม่เป็น null หรือ undefined

ตัวอย่างข้อมูลทดสอบ

> db.demo35.insertOne({"Name":"Chris"});
> db.demo35.insertOne({"Name":null});
> db.demo35.insertOne({"Name":"Bob"});
> db.demo35.insertOne({"Name":undefined});

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

> db.demo35.find();
{
    "_id" : ObjectId("5e175e42cfb11e5c34d898d0"),
    "Name" : "Chris"
}
{
    "_id" : ObjectId("5e175e46cfb11e5c34d898d1"),
    "Name" : null
}
{
    "_id" : ObjectId("5e175e4bcfb11e5c34d898d2"),
    "Name" : "Bob"
}
{
    "_id" : ObjectId("5e175e54cfb11e5c34d898d3"),
    "Name" : undefined
}

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

> db.demo35.find({"Name": {$ne: null}});

ผลลัพธ์ (เหลือเฉพาะที่มีค่า)

{
    "_id" : ObjectId("5e175e42cfb11e5c34d898d0"),
    "Name" : "Chris"
}
{
    "_id" : ObjectId("5e175e4bcfb11e5c34d898d2"),
    "Name" : "Bob"
}

หมายเหตุ: $ne: null จะข้ามทั้ง null และ undefined (MongoDB ถือ undefined เทียบเท่า null ในการเปรียบเทียบ) หากต้องการข้ามเฉพาะ null ต้องใช้ {$and: [{"Name": {$ne: null}}, {"Name": {$exists: true}}]}