SQL에서 자주 사용하는 WHERE IN(1,2,...) 조건은 MongoDB에서 $in 연산자로 동일하게 구현할 수 있습니다. $in 연산자는 필드 값이 지정한 배열 내 값 중 하나와 일치하는 문서만 조회하고 싶을 때 매우 유용합니다.
$in 연산자 기본 문법
$in 연산자의 기본적인 사용 형식은 다음과 같습니다.
db.yourCollectionName.find({yourFieldName:{$in:[yourValue1,yourValue2,....N]}}).pretty();배열 안에 조회하고 싶은 값을 나열하기만 하면 되므로, SQL의 IN 절보다 오히려 직관적이라고 할 수 있습니다.
예제용 컬렉션 생성하기
먼저 실습에 사용할 컬렉션을 만들고 문서를 삽입해 보겠습니다. 학생 이름과 수학 점수를 저장하는 간단한 예제입니다.
> db.whereInDemo.insertOne({"StudentName":"John","StudentMathScore":57});
{
"acknowledged" : true,
"insertedId" : ObjectId("5ca281ec6304881c5ce84ba5")
}
> db.whereInDemo.insertOne({"StudentName":"Larry","StudentMathScore":89});
{
"acknowledged" : true,
"insertedId" : ObjectId("5ca281f56304881c5ce84ba6")
}
> db.whereInDemo.insertOne({"StudentName":"Chris","StudentMathScore":98});
{
"acknowledged" : true,
"insertedId" : ObjectId("5ca281fd6304881c5ce84ba7")
}
> db.whereInDemo.insertOne({"StudentName":"Robert","StudentMathScore":99});
{
"acknowledged" : true,
"insertedId" : ObjectId("5ca2820a6304881c5ce84ba8")
}
> db.whereInDemo.insertOne({"StudentName":"Bob","StudentMathScore":97});
{
"acknowledged" : true,
"insertedId" : ObjectId("5ca282206304881c5ce84ba9")
}총 5명의 학생 데이터가 저장되었습니다. 이제 find() 메서드를 사용해 컬렉션의 모든 문서를 확인해 보겠습니다.
> db.whereInDemo.find().pretty();
위 쿼리를 실행하면 다음과 같은 결과가 출력됩니다.
{
"_id" : ObjectId("5ca281ec6304881c5ce84ba5"),
"StudentName" : "John",
"StudentMathScore" : 57
}
{
"_id" : ObjectId("5ca281f56304881c5ce84ba6"),
"StudentName" : "Larry",
"StudentMathScore" : 89
}
{
"_id" : ObjectId("5ca281fd6304881c5ce84ba7"),
"StudentName" : "Chris",
"StudentMathScore" : 98
}
{
"_id" : ObjectId("5ca2820a6304881c5ce84ba8"),
"StudentName" : "Robert",
"StudentMathScore" : 99
}
{
"_id" : ObjectId("5ca282206304881c5ce84ba9"),
"StudentName" : "Bob",
"StudentMathScore" : 97
}$in 연산자로 특정 값 조회하기
이제 본격적으로 $in 연산자를 사용해 보겠습니다. 수학 점수가 97, 98, 99점인 학생만 조회하는 쿼리입니다. SQL로 표현하면 WHERE StudentMathScore IN (97, 98, 99)와 같습니다.
> db.whereInDemo.find({StudentMathScore:{$in:[97,98,99]}}).pretty();실행 결과는 다음과 같습니다.
{
"_id" : ObjectId("5ca281fd6304881c5ce84ba7"),
"StudentName" : "Chris",
"StudentMathScore" : 98
}
{
"_id" : ObjectId("5ca2820a6304881c5ce84ba8"),
"StudentName" : "Robert",
"StudentMathScore" : 99
}
{
"_id" : ObjectId("5ca282206304881c5ce84ba9"),
"StudentName" : "Bob",
"StudentMathScore" : 97
}결과를 보면 점수가 57점인 John과 89점인 Larry는 제외되고, 지정한 세 값(97, 98, 99) 중 하나와 일치하는 Chris, Robert, Bob의 문서만 정확히 반환된 것을 확인할 수 있습니다.
정리
MongoDB에서 SQL의 WHERE IN 조건이 필요하다면 $in 연산자를 사용하면 됩니다. 문자열뿐 아니라 숫자, 날짜 등 다양한 데이터 타입에도 적용할 수 있으며, 반대로 배열 내 값과 일치하지 않는 문서를 찾으려면 $nin 연산자를 사용하면 됩니다. 두 연산자를 함께 익혀두면 조건 조회 쿼리를 훨씬 유연하게 작성할 수 있습니다.