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

ตรวจสอบว่ามีฟิลด์กับ MongoDB หรือไม่


คุณสามารถใช้ตัวดำเนินการ $exists และ $ne สำหรับสิ่งนี้ เพื่อให้เข้าใจแนวคิดเพิ่มเติม ให้เราสร้างคอลเลกชันพร้อมเอกสาร แบบสอบถามเพื่อสร้างคอลเลกชันที่มีเอกสารมีดังนี้ -

> db.checkFieldExistDemo.insertOne({"EmployeeId":1,"EmployeeName":"John","isMarried":true,"EmployeeSalary":4648585});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c76f7b31e9c5dd6f1f78281")
}
> db.checkFieldExistDemo.insertOne({"StudentId":2,"StudentName":"John","isMarried":false," StudentAge":19});
{
   "acknowledged" : true,0
   "insertedId" : ObjectId("5c76f7e11e9c5dd6f1f78282")
}

แสดงเอกสารทั้งหมดจากคอลเล็กชันโดยใช้เมธอด find() แบบสอบถามมีดังนี้ −

> db.checkFieldExistDemo.find().pretty();

ผลลัพธ์

{
   "_id" : ObjectId("5c76f7b31e9c5dd6f1f78281"),
   "EmployeeId" : 1,
   "EmployeeName" : "John",
   "isMarried" : true,
   "EmployeeSalary" : 4648585
}
{
   "_id" : ObjectId("5c76f7e11e9c5dd6f1f78282"),
   "StudentId" : 2,
   "StudentName" : "John",
   "isMarried" : false,
   "StudentAge" : 19
}

นี่คือแบบสอบถามเพื่อตรวจสอบว่ามีฟิลด์ใน MongoDB หรือไม่

กรณีที่ 1 − เมื่อเขตข้อมูลมีอยู่ในเอกสารมากกว่าหนึ่งฉบับ แบบสอบถามมีดังนี้ −

> db.checkFieldExistDemo.find({"isMarried":{$exists:true,$ne:null}}).pretty();

ผลลัพธ์

{
   "_id" : ObjectId("5c76f7b31e9c5dd6f1f78281"),
   "EmployeeId" : 1,
   "EmployeeName" : "John",
   "isMarried" : true,
   "EmployeeSalary" : 4648585
}
{
   "_id" : ObjectId("5c76f7e11e9c5dd6f1f78282"),
   "StudentId" : 2,
   "StudentName" : "John",
   "isMarried" : false,
   "StudentAge" : 19
}

กรณีที่ 2 − เมื่อมีฟิลด์อยู่ในเอกสารเดียวเท่านั้น แบบสอบถามมีดังนี้ −

> db.checkFieldExistDemo.find({"StudentName":{$exists:true,$ne:null}}).pretty();

ผลลัพธ์

{
   "_id" : ObjectId("5c76f7e11e9c5dd6f1f78282"),
   "StudentId" : 2,
   "StudentName" : "John",
   "isMarried" : false,
   "StudentAge" : 19
}