주어진 키가 있는 레코드를 선택하려면 $exists 연산자를 사용할 수 있습니다. 구문은 다음과 같습니다 -
db.yourCollectionName.find( { yourFieldName: { $exists : true } } ).pretty(); 위의 구문을 이해하기 위해 문서로 컬렉션을 생성해 보겠습니다. 문서로 컬렉션을 생성하는 쿼리는 다음과 같습니다 -
> 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")
} find() 메서드를 사용하여 컬렉션의 모든 문서를 표시합니다. 쿼리는 다음과 같습니다 -
> 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
} 다음은 주어진 키를 가진 레코드를 선택하는 쿼리입니다 -
> 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
}