MongoDB에서 필드가 숫자인지 확인하는 방법
MongoDB에서 특정 필드의 값이 숫자인지 확인하려면 $type 연산자를 사용하면 됩니다. $type 연산자는 BSON 타입을 기준으로 문서를 조회할 수 있게 해주며, "number" 별칭(alias)을 사용하면 double, int, long, decimal 등 모든 숫자 타입을 한 번에 검색할 수 있습니다.
기본 문법
db.컬렉션명.find({필드명: {$type: "number"}}).pretty();예제 컬렉션 생성하기
먼저 테스트용 컬렉션을 만들고 문서를 삽입해 보겠습니다. 아래 예제에서는 학생 정보를 담은 컬렉션에 숫자 필드와 문자열 필드를 혼합하여 저장합니다.
> db.checkIfFieldIsNumberDemo.insertOne({"StudentName":"John","StudentAge":23});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c9ec75dd628fa4220163b83")
}
> db.checkIfFieldIsNumberDemo.insertOne({"StudentName":"Chris","StudentMathScore":98,"StudentCountryName":"US"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c9ec77cd628fa4220163b84")
}
> db.checkIfFieldIsNumberDemo.insertOne({"StudentName":"Robert","StudentCountryName":"AUS"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c9ec7a4d628fa4220163b85")
}
> db.checkIfFieldIsNumberDemo.insertOne({"StudentId":101,"StudentName":"Larry","StudentCountryName":"AUS"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c9ec7ccd628fa4220163b86")
}저장된 전체 문서 확인하기
find() 메서드를 사용해 컬렉션의 모든 문서를 조회해 보겠습니다.
> db.checkIfFieldIsNumberDemo.find().pretty();
위 쿼리를 실행하면 다음과 같은 결과가 출력됩니다.
{
"_id" : ObjectId("5c9ec75dd628fa4220163b83"),
"StudentName" : "John",
"StudentAge" : 23
}
{
"_id" : ObjectId("5c9ec77cd628fa4220163b84"),
"StudentName" : "Chris",
"StudentMathScore" : 98,
"StudentCountryName" : "US"
}
{
"_id" : ObjectId("5c9ec7a4d628fa4220163b85"),
"StudentName" : "Robert",
"StudentCountryName" : "AUS"
}
{
"_id" : ObjectId("5c9ec7ccd628fa4220163b86"),
"StudentId" : 101,
"StudentName" : "Larry",
"StudentCountryName" : "AUS"
}$type으로 숫자 필드 조회하기
이제 StudentMathScore 필드가 숫자인 문서만 조회하는 쿼리를 실행해 보겠습니다.
> db.checkIfFieldIsNumberDemo.find({StudentMathScore: {$type:"number"}}).pretty();실행 결과, 해당 필드가 숫자 타입인 문서만 정확히 반환되는 것을 확인할 수 있습니다.
{
"_id" : ObjectId("5c9ec77cd628fa4220163b84"),
"StudentName" : "Chris",
"StudentMathScore" : 98,
"StudentCountryName" : "US"
}참고: $type에서 사용 가능한 숫자 별칭
"number" 외에도 더 세분화된 타입 검사가 필요하다면 다음 별칭들을 활용할 수 있습니다.
- "double" – 배정밀도 부동소수점 (BSON 타입 1)
- "int" – 32비트 정수 (BSON 타입 16)
- "long" – 64비트 정수 (BSON 타입 18)
- "decimal" – 128비트 십진수 (BSON 타입 19)
이처럼 $type 연산자를 활용하면 스키마가 유연한 MongoDB에서도 특정 필드의 데이터 타입을 손쉽게 검증하고 조회할 수 있습니다.