Để chọn các record có chứa một khóa (field) cụ thể trong MongoDB, bạn sử dụng toán tử $exists với giá trị true.
Cú pháp
db.yourCollectionName.find( { yourFieldName: { $exists : true } } ).pretty();
Ví dụ minh họa
Tạo collection và dữ liệu
> db.selectRecordsHavingKeyDemo.insertOne({"StudentName":"John","StudentAge":21,"StudentMathMarks":78});
{ "acknowledged" : true, "insertedId" : ObjectId("5c8b7be780f10143d8431e0f") }
> db.selectRecordsHavingKeyDemo.insertOne({"StudentName":"Carol","StudentMathMarks":89});
{ "acknowledged" : true, "insertedId" : ObjectId("5c8b7bfc80f10143d8431e10") }
> db.selectRecordsHavingKeyDemo.insertOne({"StudentName":"Sam","StudentAge":26,"StudentMathMarks":89});
{ "acknowledged" : true, "insertedId" : ObjectId("5c8b7c1280f10143d8431e11") }
> db.selectRecordsHavingKeyDemo.insertOne({"StudentName":"Sam","StudentMathMarks":98});
{ "acknowledged" : true, "insertedId" : ObjectId("5c8b7c2180f10143d8431e12") }
Xem tất cả documents
> db.selectRecordsHavingKeyDemo.find().pretty();
{
"_id" : ObjectId("5c8b7be780f10143d8431e0f"),
"StudentName" : "John",
"StudentAge" : 21,
"StudentMathMarks" : 78
}
{
"_id" : ObjectId("5c8b7bfc80f10143d8431e10"),
"StudentName" : "Carol",
"StudentMathMarks" : 89
}
{
"_id" : ObjectId("5c8b7c1280f10143d8431e11"),
"StudentName" : "Sam",
"StudentAge" : 26,
"StudentMathMarks" : 89
}
{
"_id" : ObjectId("5c8b7c2180f10143d8431e12"),
"StudentName" : "Sam",
"StudentMathMarks" : 98
}
Truy vấn record có trường StudentMathMarks
> db.selectRecordsHavingKeyDemo.find( { StudentMathMarks : { $exists : true } } ).pretty();
{
"_id" : ObjectId("5c8b7be780f10143d8431e0f"),
"StudentName" : "John",
"StudentAge" : 21,
"StudentMathMarks" : 78
}
{
"_id" : ObjectId("5c8b7bfc80f10143d8431e10"),
"StudentName" : "Carol",
"StudentMathMarks" : 89
}
{
"_id" : ObjectId("5c8b7c1280f10143d8431e11"),
"StudentName" : "Sam",
"StudentAge" : 26,
"StudentMathMarks" : 89
}
{
"_id" : ObjectId("5c8b7c2180f10143d8431e12"),
"StudentName" : "Sam",
"StudentMathMarks" : 98
}
Tất cả 4 document đều có trường StudentMathMarks nên toàn bộ được trả về. Document thứ 2 và 4 không có trường StudentAge nhưng vẫn được trả về vì điều kiện chỉ kiểm tra StudentMathMarks.
Kết hợp với điều kiện khác
Bạn có thể kết hợp $exists với các điều kiện khác:
// Có StudentMathMarks VÀ StudentAge > 20
db.selectRecordsHavingKeyDemo.find({
StudentMathMarks: { $exists: true },
StudentAge: { $gt: 20 }
}).pretty();