Trong trường hợp này, hãy sử dụng khái niệm chỉ mục trên một trường cụ thể. Đầu tiên chúng ta hãy tạo một bộ sưu tập với các tài liệu. Ở đây, chúng tôi đã tạo chỉ mục cũng như sử dụng createIndex () -
> db.decreasetimeusingindex.createIndex({"StudentName":1});
{
"createdCollectionAutomatically" : true,
"numIndexesBefore" : 1,
"numIndexesAfter" : 2,
"ok" : 1
}
> db.decreasetimeusingindex.insertOne({"StudentName":"John Smith","StudentAge":21});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e03960af5e889d7a51994ff")
}
> db.decreasetimeusingindex.insertOne({"StudentName":"John Doe","StudentAge":24});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e039611f5e889d7a5199500")
}
> db.decreasetimeusingindex.insertOne({"StudentName":"Adam Smith","StudentAge":22});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e03961df5e889d7a5199501")
} 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.decreasetimeusingindex.find().pretty();
Điều này sẽ tạo ra kết quả sau -
{
"_id" : ObjectId("5e03960af5e889d7a51994ff"),
"StudentName" : "John Smith",
"StudentAge" : 21
}
{
"_id" : ObjectId("5e039611f5e889d7a5199500"),
"StudentName" : "John Doe",
"StudentAge" : 24
}
{
"_id" : ObjectId("5e03961df5e889d7a5199501"),
"StudentName" : "Adam Smith",
"StudentAge" : 22
} Sau đây là truy vấn để tìm một bản ghi cụ thể -
> db.decreasetimeusingindex.find({"StudentName":"Adam Smith"}); Điều này sẽ tạo ra kết quả sau -
{ "_id" : ObjectId("5e03961df5e889d7a5199501"), "StudentName" : "Adam Smith", "StudentAge" : 22 }