가능한 MongoDB의 서버 버전에 따라
db.getCollection('collection').aggregate([
{ "$addFields": {
"orderitems": {
"$map": {
"input": "$orderitems",
"as": "o",
"in": {
"description": "$$o.description",
"proposals": {
"$arrayElemAt": [
"$$o.proposals",
{ "$indexOfArray": [
"$$o.proposals.value",
{ "$min": "$$o.proposals.value" }
]}
]
}
}
}
}
}}
])
또는 MongoDB를 3.2로 할 수 있습니다 $filter
및 첫 번째 일치 요소를 $arrayElemAt
:
db.getCollection('collection').aggregate([
{ "$addFields": {
"orderitems": {
"$map": {
"input": "$orderitems",
"as": "o",
"in": {
"description": "$$o.description",
"proposals": {
"$arrayElemAt": [
{ "$filter": {
"input": "$$o.proposals",
"cond": { "$eq": ["$$this.value",{ "$min": "$$o.proposals.value" }] }
}},
0
]
}
}
}
}
}}
])
그리고 솔직히 그보다 더 낮은 버전에서는 구현하려고 애쓰는 편이 낫습니다.
필수 원칙은 $min
에 의해 반환 된 값을 기반으로하는 일치입니다. MongoDB 3.2에서 변경 사항을 얻었으므로 "누적 기"대신 모든 값 배열에서 "최소"값을 반환하는 데 사용할 수 있습니다. 집계에
$group
버전 3.2에서 변경 : $ 분은 $ 그룹과 $ 프로젝트 단계에서 사용할 수 있습니다. 이전 버전의 MongoDB에서, $ min은 $ group 단계에서만 사용 가능합니다.
그래서 일반적인 경우 우리가 $filter
의 배열 일치하는 항목으로 반환됩니다 어떤 $indexOfArray
의 일치 지수 나로 인해서 반환 값으로 배열의 항목과 일치합니다.
선택한 방법에 따라 'matched index'가 $arrayElemAt
으로 입력되어 해당 인덱스에서 배열 값을 추출하거나 0
인덱스를 사용하여 "필터링 된 목록"에서 "첫 번째"요소를 가져옵니다.
어느 접근 반환 :
{
"requester" : "test",
"orderitems" : [
{
"description" : "testitem1",
"proposals" : {
"company" : "company2",
"value" : 5.0
}
}
]
}