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

MongoDB에서 필드 값에 관계없이 특정 필드가 존재하는 모든 문서를 조회하는 방법

MongoDB에서 어떤 필드의 값이 무엇이든 상관없이 그 필드 자체가 존재하는 모든 문서를 조회하려면 $exists 연산자를 사용하면 됩니다. 이 연산자는 필드의 실제 값을 비교하는 것이 아니라, 문서 안에 해당 필드가 존재하는지 여부만 검사합니다.

$exists 연산자 기본 문법

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

예제 컬렉션 생성

먼저 테스트용 컬렉션을 만들고 문서를 삽입해 보겠습니다. 아래 예제에는 StudentAge 필드가 null이거나 빈 문자열("")인 문서도 포함되어 있습니다.

> db.findAllDocumentWhichHaveFieldDemo.insertOne({"StudentName":"John","StudentAge":null});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c9d1d60a629b87623db1b22")
}
> db.findAllDocumentWhichHaveFieldDemo.insertOne({"StudentName":"Larry","StudentAge":null});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c9d1d70a629b87623db1b23")
}
> db.findAllDocumentWhichHaveFieldDemo.insertOne({"StudentName":"Chris","StudentAge":""});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c9d1d7ba629b87623db1b24")
}
> db.findAllDocumentWhichHaveFieldDemo.insertOne({"StudentName":"Robert","StudentAge":""});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c9d1d81a629b87623db1b25")
}

저장된 전체 문서 확인

find() 메서드와 pretty()를 사용해 컬렉션의 모든 문서를 출력해 보겠습니다.

> db.findAllDocumentWhichHaveFieldDemo.find().pretty();

위 쿼리를 실행하면 다음과 같은 결과가 출력됩니다.

{
   "_id" : ObjectId("5c9d1d60a629b87623db1b22"),
   "StudentName" : "John",
   "StudentAge" : null
}
{
   "_id" : ObjectId("5c9d1d70a629b87623db1b23"),
   "StudentName" : "Larry",
   "StudentAge" : null
}
{
   "_id" : ObjectId("5c9d1d7ba629b87623db1b24"),
   "StudentName" : "Chris",
   "StudentAge" : ""
}
{
   "_id" : ObjectId("5c9d1d81a629b87623db1b25"),
   "StudentName" : "Robert",
   "StudentAge" : ""
}

$exists로 필드 존재 여부 조회하기

이제 StudentAge 필드의 값이 null이든 빈 문자열이든 관계없이, 이 필드를 가진 모든 문서를 조회하는 쿼리입니다.

> db.findAllDocumentWhichHaveFieldDemo.find({StudentAge:{$exists:true}});

실행 결과를 보면 null 값과 빈 문자열 값을 가진 문서까지 모두 포함되어 출력됩니다.

{ "_id" : ObjectId("5c9d1d60a629b87623db1b22"), "StudentName" : "John", "StudentAge" : null }
{ "_id" : ObjectId("5c9d1d70a629b87623db1b23"), "StudentName" : "Larry", "StudentAge" : null }
{ "_id" : ObjectId("5c9d1d7ba629b87623db1b24"), "StudentName" : "Chris", "StudentAge" : "" }
{ "_id" : ObjectId("5c9d1d81a629b87623db1b25"), "StudentName" : "Robert", "StudentAge" : "" }

특정 필드를 제외하고 조회하기

결과에서 StudentName 필드를 제외하고 싶다면 프로젝션(projection) 옵션을 함께 사용하면 됩니다. 첫 번째 인자에는 조회 조건을, 두 번째 인자에는 표시할 필드를 지정합니다.

> db.findAllDocumentWhichHaveFieldDemo.find({StudentAge:{$exists:true}},{StudentName:0});

실행 결과 StudentName 필드가 제외된 문서만 출력됩니다.

{ "_id" : ObjectId("5c9d1d60a629b87623db1b22"), "StudentAge" : null }
{ "_id" : ObjectId("5c9d1d70a629b87623db1b23"), "StudentAge" : null }
{ "_id" : ObjectId("5c9d1d7ba629b87623db1b24"), "StudentAge" : "" }
{ "_id" : ObjectId("5c9d1d81a629b87623db1b25"), "StudentAge" : "" }

추가 팁

$exists:false를 사용하면 반대로 해당 필드가 없는 문서만 조회할 수 있습니다. 또한 주의할 점은, 필드 값이 null이라도 필드 자체가 문서에 존재하면 $exists:true 조건에 부합한다는 것입니다. 따라서 "값이 있는 문서"를 찾으려면 $exists와 $ne:null 같은 조건을 함께 사용하는 것이 좋습니다.