MongoDB 문서의 필드에 값이 존재하는지 확인하는 방법
MongoDB에서 문서의 특정 필드에 값이 존재하는지 확인하려면 find() 메서드와 $exists 연산자를 함께 사용하면 됩니다. 이 글에서는 예제 컬렉션을 직접 만들어 보고, 배열 필드에 실제 값이 들어 있는 문서만 골라내는 과정을 단계별로 살펴보겠습니다.
1단계: 예제 컬렉션 생성
먼저 insertOne() 메서드로 테스트용 문서들을 삽입합니다. 일부 문서는 PlayerScores 배열에 값이 있고, 일부는 빈 배열([])을 가지고 있습니다.
> db.checkIfValueDemo.insertOne({"PlayerName":"John Smith","PlayerScores":[5000,98595858,554343]});
{
"acknowledged" : true,
"insertedId" : ObjectId("5cc6f507af8e7a4ca6b2ad98")
}
> db.checkIfValueDemo.insertOne({"PlayerName":"John Doe","PlayerScores":[]});
{
"acknowledged" : true,
"insertedId" : ObjectId("5cc6f512af8e7a4ca6b2ad99")
}
> db.checkIfValueDemo.insertOne({"PlayerName":"Carol Taylor","PlayerScores":[7848474,8746345353]});
{
"acknowledged" : true,
"insertedId" : ObjectId("5cc6f521af8e7a4ca6b2ad9a")
}
> db.checkIfValueDemo.insertOne({"PlayerName":"David Miller","PlayerScores":[]});
{
"acknowledged" : true,
"insertedId" : ObjectId("5cc6f531af8e7a4ca6b2ad9b")
}
2단계: 저장된 문서 전체 조회
find() 메서드를 사용해 컬렉션의 모든 문서를 확인해 보겠습니다.
> db.checkIfValueDemo.find().pretty();
위 쿼리를 실행하면 다음과 같은 결과가 출력됩니다.
{
"_id" : ObjectId("5cc6f507af8e7a4ca6b2ad98"),
"PlayerName" : "John Smith",
"PlayerScores" : [
5000,
98595858,
554343
]
}
{
"_id" : ObjectId("5cc6f512af8e7a4ca6b2ad99"),
"PlayerName" : "John Doe",
"PlayerScores" : [ ]
}
{
"_id" : ObjectId("5cc6f521af8e7a4ca6b2ad9a"),
"PlayerName" : "Carol Taylor",
"PlayerScores" : [
7848474,
8746345353
]
}
{
"_id" : ObjectId("5cc6f531af8e7a4ca6b2ad9b"),
"PlayerName" : "David Miller",
"PlayerScores" : [ ]
}
총 4개의 문서 중에서 John Doe와 David Miller의 문서는 PlayerScores 필드가 빈 배열인 것을 확인할 수 있습니다.
3단계: $exists 연산자로 값 존재 여부 확인하기
이제 값이 실제로 존재하는 문서만 조회해 보겠습니다. 아래 쿼리는 'PlayerScores.0', 즉 배열의 첫 번째 요소가 존재하는지를 $exists 연산자로 검사합니다. 배열의 첫 번째 요소가 있다는 것은 곧 빈 배열이 아니라는 의미이므로, 값이 있는 문서만 정확히 걸러낼 수 있습니다.
> db.checkIfValueDemo.find({'PlayerScores.0' : {$exists: true}}).count();
실행 결과는 다음과 같습니다.
2
결과값이 2로 나왔습니다. 이는 PlayerScores 배열에 실제 값이 존재하는 문서(John Smith, Carol Taylor)가 두 개뿐이라는 뜻입니다.
참고로 조건을 {$exists: false}로 바꾸면 반대로 첫 번째 요소가 존재하지 않는 문서, 즉 이 예제에서는 빈 배열을 가진 문서를 조회할 수 있습니다. 이처럼 점 표기법(dot notation)과 $exists 연산자를 조합하면 배열이 비어 있는지 여부까지 손쉽게 판별할 수 있습니다.