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

MongoDB에서 $in 연산자로 여러 배열 항목 조회하는 방법

MongoDB에서 특정 필드가 배열 형태일 때, 여러 값 중 하나라도 일치하는 문서를 찾고 싶다면 $in 연산자를 사용하면 됩니다. 이 글에서는 실제 예제를 통해 $in 연산자로 여러 배열 항목을 조회하는 방법을 단계별로 살펴보겠습니다.

1. 샘플 컬렉션 생성하기

먼저 개념을 이해하기 위해 문서가 포함된 컬렉션을 생성해 보겠습니다. 학생 이름과 전공 과목(StudentCoreSubject) 배열을 가진 문서 4개를 삽입합니다.

> db.findByMultipleArrayDemo.insertOne({"StudentFirstName":"John","StudentLastName":"Smith",
    "StudentCoreSubject":["Compiler","Operating System","Computer Networks"]});
{
    "acknowledged" : true,
    "insertedId" : ObjectId("5c7ef07b559dd2396bcfbfc4")
}
> db.findByMultipleArrayDemo.insertOne({"StudentFirstName":"Carol","StudentLastName":"Taylor",
    "StudentCoreSubject":["MongoDB","MySQL","SQL Server"]});
{
    "acknowledged" : true,
    "insertedId" : ObjectId("5c7ef09d559dd2396bcfbfc5")
}
> db.findByMultipleArrayDemo.insertOne({"StudentFirstName":"Bob","StudentLastName":"Taylor",
    "StudentCoreSubject":["MongoDB","MySQL","SQL Server"]});
{
    "acknowledged" : true,
    "insertedId" : ObjectId("5c7ef0c7559dd2396bcfbfc6")
}
> db.findByMultipleArrayDemo.insertOne({"StudentFirstName":"David","StudentLastName":"Johnson",
    "StudentCoreSubject":["Compiler","Operating System","Computer Networks"]});
{
    "acknowledged" : true,
    "insertedId" : ObjectId("5c7ef0f2559dd2396bcfbfc7")
}

2. 저장된 전체 문서 확인하기

find() 메서드를 사용하면 컬렉션에 저장된 모든 문서를 조회할 수 있습니다.

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

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

{
    "_id" : ObjectId("5c7ef07b559dd2396bcfbfc4"),
    "StudentFirstName" : "John",
    "StudentLastName" : "Smith",
    "StudentCoreSubject" : [
        "Compiler",
        "Operating System",
        "Computer Networks"
    ]
}
{
    "_id" : ObjectId("5c7ef09d559dd2396bcfbfc5"),
    "StudentFirstName" : "Carol",
    "StudentLastName" : "Taylor",
    "StudentCoreSubject" : [
        "MongoDB",
        "MySQL",
        "SQL Server"
    ]
}
{
    "_id" : ObjectId("5c7ef0c7559dd2396bcfbfc6"),
    "StudentFirstName" : "Bob",
    "StudentLastName" : "Taylor",
    "StudentCoreSubject" : [
        "MongoDB",
        "MySQL",
        "SQL Server"
    ]
}
{
    "_id" : ObjectId("5c7ef0f2559dd2396bcfbfc7"),
    "StudentFirstName" : "David",
    "StudentLastName" : "Johnson",
    "StudentCoreSubject" : [
        "Compiler",
        "Operating System",
        "Computer Networks"
    ]
}

3. $in 연산자로 여러 배열 항목 조회하기

이제 $in 연산자를 사용하여 배열 내 여러 값 중 하나라도 포함된 문서만 조회해 보겠습니다. 아래 쿼리는 StudentCoreSubject 배열에 "Compiler" 또는 "Computer Networks"가 포함된 모든 문서를 찾습니다.

> db.findByMultipleArrayDemo.find({ StudentCoreSubject: { $in: ["Compiler", "Computer Networks"] }}).pretty();

실행 결과는 다음과 같습니다.

{
    "_id" : ObjectId("5c7ef07b559dd2396bcfbfc4"),
    "StudentFirstName" : "John",
    "StudentLastName" : "Smith",
    "StudentCoreSubject" : [
        "Compiler",
        "Operating System",
        "Computer Networks"
    ]
}
{
    "_id" : ObjectId("5c7ef0f2559dd2396bcfbfc7"),
    "StudentFirstName" : "David",
    "StudentLastName" : "Johnson",
    "StudentCoreSubject" : [
        "Compiler",
        "Operating System",
        "Computer Networks"
    ]
}

$in 연산자의 동작 원리 정리

결과를 보면 John과 David의 문서만 반환되었습니다. 두 학생의 전공 과목 배열에는 "Compiler" 또는 "Computer Networks"가 포함되어 있기 때문입니다. 반면 Carol과 Bob은 MongoDB, MySQL, SQL Server만 가지고 있어 조건에 해당하지 않으므로 제외되었습니다.

이처럼 $in 연산자는 지정한 값 목록 중 하나라도 일치하면 해당 문서를 반환합니다. 배열 필드뿐 아니라 일반 필드에서도 동일하게 사용할 수 있으며, OR 조건 검색을 간결하게 표현할 때 매우 유용합니다. 만약 배열의 모든 요소가 일치해야 하는 경우라면 $all 연산자를 사용하는 것이 적합합니다.