Để sử dụng MongoDB để tìm tất cả các tài liệu có một trường, bất kể giá trị của trường đó là bao nhiêu, hãy sử dụng toán tử $ being. Sau đây là cú pháp
db.yourCollectionName.find({yourFieldName:{$exists:true}}); Hãy để chúng tôi tạo một bộ sưu tập với các tài liệu
>db.findAllDocumentWhichHaveFieldDemo.insertOne({"StudentName":"John","StudentAge":null});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c9d1d60a629b87623db1b22")
}
>db.findAllDocumentWhichHaveFieldDemo.insertOne({"StudentName":"Larry","StudentAge":null});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c9d1d70a629b87623db1b23")
}
>db.findAllDocumentWhichHaveFieldDemo.insertOne({"StudentName":"Chris","StudentAge":""});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c9d1d7ba629b87623db1b24")
}
>db.findAllDocumentWhichHaveFieldDemo.insertOne({"StudentName":"Robert","StudentAge":""});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c9d1d81a629b87623db1b25")
} 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.findAllDocumentWhichHaveFieldDemo.find().pretty();
Điều này sẽ tạo ra kết quả sau
{
"_id" : ObjectId("5c9d1d60a629b87623db1b22"),
"StudentName" : "John",
"StudentAge" : null
}
{
"_id" : ObjectId("5c9d1d70a629b87623db1b23"),
"StudentName" : "Larry",
"StudentAge" : null
}
{
"_id" : ObjectId("5c9d1d7ba629b87623db1b24"),
"StudentName" : "Chris",
"StudentAge" : ""
}
{
"_id" : ObjectId("5c9d1d81a629b87623db1b25"),
"StudentName" : "Robert",
"StudentAge" : ""
} Sau đây là truy vấn sử dụng MongoDB để tìm tất cả các tài liệu có một trường, bất kể giá trị của trường đó là bao nhiêu
> db.findAllDocumentWhichHaveFieldDemo.find({StudentAge:{$exists:true}}); Điều này sẽ tạo ra kết quả sau
{
"_id" : ObjectId("5c9d1d60a629b87623db1b22"),
"StudentName" : "John",
"StudentAge" : null
}
{
"_id" : ObjectId("5c9d1d70a629b87623db1b23"),
"StudentName" : "Larry",
"StudentAge" : null
}
{
"_id" : ObjectId("5c9d1d7ba629b87623db1b24"),
"StudentName" : "Chris",
"StudentAge" : ""
}
{
"_id" : ObjectId("5c9d1d81a629b87623db1b25"),
"StudentName" : "Robert",
"StudentAge" : ""
} Sau đây là truy vấn nếu bạn không muốn trường “StudentName” trong kết quả
>db.findAllDocumentWhichHaveFieldDemo.find({},{StudentName:0},{StudentAge:{$exists:true}}); Điều này sẽ tạo ra kết quả sau
{ "_id" : ObjectId("5c9d1d60a629b87623db1b22"), "StudentAge" : null }
{ "_id" : ObjectId("5c9d1d70a629b87623db1b23"), "StudentAge" : null }
{ "_id" : ObjectId("5c9d1d7ba629b87623db1b24"), "StudentAge" : "" }
{ "_id" : ObjectId("5c9d1d81a629b87623db1b25"), "StudentAge" : "" }