Để truy vấn giá trị null trong MongoDB, hãy sử dụng toán tử $ ne. Trước tiên, hãy để chúng tôi tạo một bộ sưu tập với các tài liệu -
> db.queryingNullDemo.insertOne(
... {
... "StudentName":"Larry",
... "StudentDetails":
... {
... "StudentAge":21,
... "StudentSubject":"MongoDB"
... }
... }
... );
{
"acknowledged" : true,
"insertedId" : ObjectId("5cd00bec588d4a6447b2e05f")
}
> db.queryingNullDemo.insertOne(
... {
... "StudentName":"Sam",
... "StudentDetails":
... {
... "StudentAge":23,
... "StudentSubject":null
... }
... }
... );
{
"acknowledged" : true,
"insertedId" : ObjectId("5cd00c00588d4a6447b2e060")
} Sau đây là truy vấn để hiển thị tất cả các tài liệu từ một bộ sưu tập với sự trợ giúp của phương thức find () -
> db.queryingNullDemo.find().pretty();
Điều này sẽ tạo ra kết quả sau -
{
"_id" : ObjectId("5cd00bec588d4a6447b2e05f"),
"StudentName" : "Larry",
"StudentDetails" : {
"StudentAge" : 21,
"StudentSubject" : "MongoDB"
}
}
{
"_id" : ObjectId("5cd00c00588d4a6447b2e060"),
"StudentName" : "Sam",
"StudentDetails" : {
"StudentAge" : 23,
"StudentSubject" : null
}
} Sau đây là cách bạn có thể truy vấn null -
> db.queryingNullDemo.find({'StudentDetails.StudentSubject': {$ne: null}}); Điều này sẽ tạo ra kết quả sau -
{ "_id" : ObjectId("5cd00bec588d4a6447b2e05f"),
"StudentName" : "Larry",
"StudentDetails" : { "StudentAge" : 21, "StudentSubject" : "MongoDB" } }