Computer >> 컴퓨터 >  >> 프로그래밍 >> MongoDB

MongoDB에서 특정 키(필드)를 가진 레코드를 선택하는 쿼리 방법

MongoDB에서 특정 키가 있는 레코드를 선택하는 방법

MongoDB에서 특정 필드(키)를 가지고 있는 문서만 골라서 조회하고 싶다면 $exists 연산자를 활용하면 됩니다. 이 연산자는 지정한 필드가 문서 안에 실제로 존재하는지 여부를 판단하여, 조건에 맞는 레코드만 반환해 줍니다.

기본 문법

db.yourCollectionName.find({ yourFieldName: { $exists: true } }).pretty();

$exists에 true를 지정하면 해당 필드가 존재하는 문서만 조회되고, false를 지정하면 반대로 필드가 존재하지 않는 문서만 조회됩니다.

예제용 컬렉션 만들기

동작을 직접 확인하기 위해 먼저 샘플 데이터를 준비하겠습니다. 아래 쿼리는 selectRecordsHavingKeyDemo 컬렉션에 학생 정보를 담은 문서를 차례로 삽입합니다. 비교를 위해 일부러 StudentAge 필드가 빠져 있는 문서도 함께 넣었습니다.

> 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
}

$exists 연산자로 특정 키를 가진 레코드 선택하기

이번에는 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
}

네 개의 문서가 모두 StudentMathMarks 필드를 가지고 있기 때문에 전체 문서가 그대로 반환된 것을 확인할 수 있습니다. 만약 반대로 특정 필드가 없는 문서를 찾고 싶다면 $exists 값을 false로 변경하면 됩니다. 예를 들어 { StudentAge: { $exists: false } } 조건으로 조회하면 StudentAge 필드가 없는 Carol과 Sam(98점) 두 문서만 결과로 나타납니다.