이 경우 특정 필드에 대한 인덱스 개념을 사용합니다. 먼저 문서로 컬렉션을 만들어 보겠습니다. 여기에서 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")
} 다음은 find() 메서드를 사용하여 컬렉션의 모든 문서를 표시하는 쿼리입니다. -
> db.decreasetimeusingindex.find().pretty();
이것은 다음과 같은 출력을 생성합니다 -
{
"_id" : ObjectId("5e03960af5e889d7a51994ff"),
"StudentName" : "John Smith",
"StudentAge" : 21
}
{
"_id" : ObjectId("5e039611f5e889d7a5199500"),
"StudentName" : "John Doe",
"StudentAge" : 24
}
{
"_id" : ObjectId("5e03961df5e889d7a5199501"),
"StudentName" : "Adam Smith",
"StudentAge" : 22
} 다음은 특정 레코드를 찾는 쿼리입니다 -
> db.decreasetimeusingindex.find({"StudentName":"Adam Smith"}); 이것은 다음과 같은 출력을 생성합니다 -
{ "_id" : ObjectId("5e03961df5e889d7a5199501"), "StudentName" : "Adam Smith", "StudentAge" : 22 }