Để chọn các bản ghi có một khóa nhất định, bạn có thể sử dụng toán tử $ being. Cú pháp như sau -
db.yourCollectionName.find( { yourFieldName: { $exists : true } } ).pretty(); Để hiểu cú pháp trên, chúng ta hãy tạo một bộ sưu tập với tài liệu. Truy vấn để tạo một bộ sưu tập với một tài liệu như sau -
> 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")
} 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 (). Truy vấn như sau -
> db.selectRecordsHavingKeyDemo.find().pretty();
Sau đây là kết quả -
{
"_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
} Đây là truy vấn để chọn các bản ghi có một khóa nhất định -
> db.selectRecordsHavingKeyDemo.find( { StudentMathMarks : { $exists : true } } ).pretty(); Sau đây là kết quả -
{
"_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
}