Make the MongoDB docs better! We value your opinion. Share your feedback for a chance to win $100.
Click here >
Docs Menu
Docs Home
/ /

$ 필터하다 (표현식 연산자)

$filter

지정된 조건을 바탕으로 반환할 배열의 하위 집합을 선택합니다. 조건과 일치하는 요소만 포함되어 있는 배열을 반환하며, 반환된 요소는 원래 순서대로 표시됩니다.

다음 환경에서 호스팅되는 배포에 $filter 사용할 수 있습니다.

  • MongoDB Atlas: 클라우드에서의 MongoDB 배포를 위한 완전 관리형 서비스

  • MongoDB Enterprise: MongoDB의 구독 기반 자체 관리 버전

  • MongoDB Community: MongoDB의 소스 사용 가능 무료 자체 관리 버전

$filter 의 구문은 다음과 같습니다:

{
$filter:
{
input: <array>,
as: <string>,
arrayIndexAs: <string>,
cond: <expression>,
limit: <number expression>
}
}
필드
사양

input

배열로 해석되는 표현식 입니다.

input 값이 null로 확인되거나 누락된 필드를 나타내는 경우 $filternull을 반환합니다.

input이 배열과 null이 아닌 값으로 해석되면 파이프라인 오류가 발생합니다.

as

선택 사항. input 배열의 각 개별 요소를 나타내는 변수의 이름입니다. 이름을 지정하지 않으면 변수 이름은 기본적으로 this가 됩니다.

arrayIndexAs

선택 사항. 배열 에 있는 현재 요소의 인덱스 를 나타내는 집계 변수의 input 이름입니다. 첫 번째 배열 요소 인덱스 0 입니다.

표현식 에 변수 이름을 사용할 수 있습니다. 예시 들어 arrayIndexAs: "myIndex"을 지정하면 표현식 에 $$myIndex 이 사용됩니다. $$myIndexinput 배열 에 있는 현재 요소의 인덱스 반환합니다.

arrayIndexAs을(를) 생략하면 표현식 에 시스템 변수를 사용하여 현재 요소의 인덱스 반환할 수 있습니다.$$IDX

예제는 배열에 있는 각 항목의 인덱스에 액세스하기$$IDX 사용하여 인덱스에 액세스하기 항목을 참조하세요.

버전 8.3에 추가 되었습니다.

cond

요소를 출력 배열에 포함할지 여부를 결정하는 데 사용되는 부울 값으로 해석되는 표현식입니다. 표현식은 as에 지정된 변수 이름을 사용하여 input 배열의 각 요소를 개별적으로 참고합니다.

limit

선택 사항. 가 $filter 반환하는 일치하는 배열 요소의 수를 제한하는 숫자 표현식 입니다. 1보다 작은 제한은 지정할 수 없습니다. 일치하는 배열 요소는 입력 배열 에 나타나는 순서대로 반환됩니다.

지정된 이 limit 일치하는 배열 요소의 수보다 크면 는 일치하는 모든 배열 요소를$filter 반환합니다. 제한이 인 경우 null $filter 는 일치하는 모든 배열 요소를 반환합니다.

표현식에 대한 자세한 내용은 표현식을 참조하세요 .

예시
결과
{
$filter: {
input: [ 1, "a", 2, null, 3.1, Long(4), "5" ],
as: "num",
cond: { $isNumber: "$$num" }
}
}

[ 1, 2, 3.1, Long(4) ]

{
$filter: {
input: [ 1, "a", 2, null, 3.1, Long(4), "5" ],
as: "num",
cond: { $isNumber: "$$num" },
limit: 2
}
}

[ 1, 2 ]

{
$filter: {
input: [ 1, "a", 2, null, 3.1, Long(4), "5" ],
as: "num",
cond: { $isNumber: "$$num" },
limit: { $add: [ 0, 1 ] }
}
}

[ 1 ]

컬렉션 sales에는 다음 문서가 있습니다.

db.sales.insertMany( [
{
_id: 0,
items: [
{ item_id: 43, quantity: 2, price: 10, name: "pen" },
{ item_id: 2, quantity: 1, price: 240, name: "briefcase" }
]
},
{
_id: 1,
items: [
{ item_id: 23, quantity: 3, price: 110, name: "notebook" },
{ item_id: 103, quantity: 4, price: 5, name: "pen" },
{ item_id: 38, quantity: 1, price: 300, name: "printer" }
]
},
{
_id: 2,
items: [
{ item_id: 4, quantity: 1, price: 23, name: "paper" }
]
}
] )

다음 예시에서는 100보다 크거나 같은 price가 있는 문서만 포함하도록 items 배열을 필터링합니다.

db.sales.aggregate( [
{
$project: {
items: {
$filter: {
input: "$items",
as: "item",
cond: { $gte: [ "$$item.price", 100 ] }
}
}
}
}
] )
[
{
_id: 0,
items: [ { item_id: 2, quantity: 1, price: 240, name: 'briefcase' } ]
},
{
_id: 1,
items: [
{ item_id: 23, quantity: 3, price: 110, name: 'notebook' },
{ item_id: 38, quantity: 1, price: 300, name: 'printer' }
]
},
{ _id: 2, items: [] }
]

이 예시에서는 이전 예시의 sales 컬렉션을 사용합니다.

이 예시에서는 limit 필드를 사용하여 각 items 배열에 반환된 일치하는 요소 수를 지정합니다.

db.sales.aggregate( [
{
$project: {
items: {
$filter: {
input: "$items",
as: "item",
cond: { $gte: [ "$$item.price", 100 ] },
limit: 1
}
}
}
}
] )
[
{
_id: 0,
items: [ { item_id: 2, quantity: 1, price: 240, name: 'briefcase' } ]
},
{
_id: 1,
items: [ { item_id: 23, quantity: 3, price: 110, name: 'notebook' } ]
},
{ _id: 2, items: [] }
]

이 예시에서는 이전 예시의 sales 컬렉션을 사용합니다.

이 예시에서는 반환될 수 있는 일치하는 요소의 수보다 큰 limit 필드 값을 사용합니다. 이 경우 limit은(는) 쿼리 결과에 영향을 주지 않으며 $gte 필터 조건과 일치하는 모든 문서를 반환합니다.

db.sales.aggregate( [
{
$project: {
items: {
$filter: {
input: "$items",
as: "item",
cond: { $gte: [ "$$item.price", 100] },
limit: 5
}
}
}
}
] )
[
{
_id: 0,
items: [ { item_id: 2, quantity: 1, price: 240, name: 'briefcase' } ]
},
{
_id: 1,
items: [
{ item_id: 23, quantity: 3, price: 110, name: 'notebook' },
{ item_id: 38, quantity: 1, price: 300, name: 'printer' }
]
},
{ _id: 2, items: [] }
]

이 예시에서는 이전 예시의 sales 컬렉션을 사용합니다.

name 값이 penitems의 집계 필터는 다음과 같습니다.

db.sales.aggregate( [
{
$project: {
items: {
$filter: {
input: "$items",
as: "item",
cond: { $eq: [ "$$item.name", "pen"] }
}
}
}
}
] )
[
{
_id: 0,
items: [ { item_id: 43, quantity: 2, price: 10, name: 'pen' } ]
},
{
_id: 1,
items: [ { item_id: 103, quantity: 4, price: 5, name: 'pen' } ]
},
{ _id: 2, items: [] }
]

이 예시에서는 이전 예시의 sales 컬렉션을 사용합니다.

다음 집계는 $regexMatch을(를) 사용하여 p(으)로 시작하는 name 값이 있는 items을(를) 필터링합니다.

db.sales.aggregate( [
{
$project: {
items: {
$filter: {
input: "$items",
as: "item",
cond: {
$regexMatch: { input: "$$item.name", regex: /^p/ }
}
}
}
}
}
] )
[
{
_id: 0,
items: [ { item_id: 43, quantity: 2, price: 10, name: 'pen' } ]
},
{
_id: 1,
items: [
{ item_id: 103, quantity: 4, price: 5, name: 'pen' },
{ item_id: 38, quantity: 1, price: 300, name: 'printer' }
]
},
{
_id: 2,
items: [ { item_id: 4, quantity: 1, price: 23, name: 'paper' } ]
}
]

이 문서를 사용하여 people 이라는 이름의 샘플 컬렉션 만듭니다.

db.people.insertMany( [
{ _id: 1, name: "Melissa", hobbies: [ "softball", "drawing", "reading" ] },
{ _id: 2, name: "Brad", hobbies: [ "gaming", "skateboarding" ] },
{ _id: 3, name: "Scott", hobbies: [ "basketball", "music", "fishing" ] },
{ _id: 4, name: "Tracey", hobbies: [ "acting", "yoga" ] },
{ _id: 5, name: "Josh", hobbies: [ "programming" ] },
{ _id: 6, name: "Claire" }
] )

hobbies 필드 에는 각 개인의 취미가 순위가 지정된 순서대로 배열 되어 있습니다. 배열 의 첫 번째 취미는 개인이 가장 많은 시간을 보내는 프라이머리 취미입니다. 첫 번째 취미는 배열 인덱스 가 0입니다.

다음 예시 arrayIndexAs를 사용합니다. myIndex 변수는 hobbies 배열 에 있는 각 취미의 인덱스 가집니다. 이 예시 다음과 같은 필드가 있는 문서를 반환합니다.

  • 사람 이름입니다.

  • secondaryHobbies 다른 모든 취미를 포함하는 배열 .

db.people.aggregate( [
{
$project: {
_id: 0,
name: 1,
secondaryHobbies: {
$filter: {
input: "$hobbies",
arrayIndexAs: "myIndex",
cond: { $eq: [ { $mod: [ "$$myIndex", 2 ] }, 0 ] }
}
}
}
}
] )

출력:

[
{ "name" : "Melissa", "secondaryHobbies" : [ "softball", "reading" ] }
{ "name" : "Brad", "secondaryHobbies" : [ "gaming" ] }
{ "name" : "Scott", "secondaryHobbies" : [ "basketball", "fishing" ] }
{ "name" : "Tracey", "secondaryHobbies" : [ "acting" ] }
{ "name" : "Josh", "secondaryHobbies" : [ "programming" ] }
{ "name" : "Claire", "secondaryHobbies" : null }
]

$$IDX 변수는 배열 에 있는 현재 요소의 인덱스 input 를 반환합니다.$$IDX 표현식 arrayIndexAs 에서 필드 생략한 경우 를 사용할 수 있습니다.

다음 예시 이전 섹션인 배열의 각 항목의 인덱스에 액세스하기 섹션의 예시 와 동일한 문서를 반환하지만 대신 $$IDXarrayIndexAs 사용합니다.

db.people.aggregate( [
{
$project: {
_id: 0,
name: 1,
secondaryHobbies: {
$filter: {
input: "$hobbies",
cond: { $eq: [ { $mod: [ "$$IDX", 2 ] }, 0 ] }
}
}
}
}
] )

돌아가기

$expMovingAvg

이 페이지의 내용