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

MongoDB $elemMatch로 배열 요소에 특정 필드가 없는 문서 조회하는 방법

MongoDB에서 배열 내 요소 중 특정 값(필드)이 존재하지 않는 문서를 조회해야 하는 경우가 있습니다. 이럴 때는 $elemMatch 연산자를 사용하면 됩니다.

$elemMatch 연산자는 지정된 모든 조건을 만족하는 요소를 하나 이상 포함한 배열 필드를 가진 문서를 매칭합니다. 여기에 $exists 연산자를 함께 사용하면 특정 필드의 존재 여부를 기준으로 문서를 필터링할 수 있습니다.

1. 샘플 컬렉션 생성

먼저 실습용 컬렉션에 문서를 삽입해 보겠습니다.

> db.demo239.insertOne(
...   {
...     "Name" : "Chris",
...     "details" : [
...        { "DueDate" : new ISODate("2019-01-21"), "ProductPrice" : 1270 },
...        { "DueDate" : new ISODate("2020-02-12"), "ProductPrice" : 2000 }
...      ]
...   }
...);
{
    "acknowledged" : true,
    "insertedId" : ObjectId("5e441c6bf4cebbeaebec5157")
}
> db.demo239.insertOne(
...   {
...     "Name" : "David",
...     "details" : [
...        { "DueDate" : new ISODate("2018-11-11"), "ProductPrice" : 1450},
...        { "DueDate" : new ISODate("2020-02-12") }
...      ]
...   }
...);
{
    "acknowledged" : true,
    "insertedId" : ObjectId("5e441c6cf4cebbeaebec5158")
}

위 예제에서 Chris의 문서는 details 배열의 모든 요소에 ProductPrice 필드가 있지만, David의 문서는 두 번째 요소에 DueDate만 있고 ProductPrice 필드가 없습니다.

2. 전체 문서 확인하기

find() 메서드를 사용하여 컬렉션의 모든 문서를 조회합니다.

> db.demo239.find();

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

{
    "_id" : ObjectId("5e441c6bf4cebbeaebec5157"), "Name" : "Chris", "details" : [
       { "DueDate" : ISODate("2019-01-21T00:00:00Z"), "ProductPrice" : 1270 },
       { "DueDate" : ISODate("2020-02-12T00:00:00Z"), "ProductPrice" : 2000 }
    ]
}
{
    "_id" : ObjectId("5e441c6cf4cebbeaebec5158"), "Name" : "David", "details" : [
       { "DueDate" : ISODate("2018-11-11T00:00:00Z"), "ProductPrice" : 1450 },
       { "DueDate" : ISODate("2020-02-12T00:00:00Z") }
    ]
}

3. 배열 요소에 특정 필드가 없는 문서 조회하기

이제 배열 요소에 특정 값(ProductPrice)이 없는 문서를 가져오는 쿼리입니다. $elemMatch 안에서 DueDate는 존재하고($exists: true), ProductPrice는 존재하지 않는($exists: false) 조건을 지정합니다.

> db.demo239.find({ "details": { "$elemMatch": { "DueDate": { "$exists": true }, "ProductPrice": { "$exists": false } } } })

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

{ "_id" : ObjectId("5e441c6cf4cebbeaebec5158"), "Name" : "David", "details" : [ { "DueDate" : ISODate("2018-11-11T00:00:00Z"), "ProductPrice" : 1450 }, { "DueDate" : ISODate("2020-02-12T00:00:00Z") } ] }

결과를 보면 ProductPrice 필드가 없는 요소를 하나라도 포함한 David의 문서만 반환된 것을 확인할 수 있습니다. 이처럼 $elemMatch$exists를 조합하면 배열 내 요소 단위로 필드의 존재 여부를 정확하게 검사할 수 있습니다.