다음을 통해 공유


$concatArrays

$concatArrays 산자는 여러 배열을 단일 배열로 결합하는 데 사용됩니다. 이 연산자는 문서의 여러 문서나 필드의 배열을 병합해야 하는 경우에 유용합니다.

문법

{
  $concatArrays: ["<array1>", "<array2>"]
}

매개 변수

매개 변수 Description
<array1>, <array2> 연결을 대상으로 하는 배열 필드입니다.

예시

스토어 컬렉션에서 이 샘플 문서를 고려합니다.

{
    "_id": "7954bd5c-9ac2-4c10-bb7a-2b79bd0963c5",
    "name": "Lakeshore Retail | DJ Equipment Stop - Port Cecile",
    "location": {
        "lat": 60.1441,
        "lon": -141.5012
    },
    "staff": {
        "totalStaff": {
            "fullTime": 2,
            "partTime": 0
        }
    },
    "sales": {
        "salesByCategory": [
            {
                "categoryName": "DJ Headphones",
                "totalSales": 35921
            },
            {
                "categoryName": "DJ Cables",
                "totalSales": 1000
            }
        ],
        "fullSales": 3700
    },
    "promotionEvents": [
        {
            "eventName": "Bargain Blitz Days",
            "promotionalDates": {
                "startDate": {
                    "Year": 2024,
                    "Month": 3,
                    "Day": 11
                },
                "endDate": {
                    "Year": 2024,
                    "Month": 2,
                    "Day": 18
                }
            },
            "discounts": [
                {
                    "categoryName": "DJ Turntables",
                    "discountPercentage": 18
                },
                {
                    "categoryName": "DJ Mixers",
                    "discountPercentage": 15
                }
            ]
        },
        {
            "eventName": "Discount Delight Days",
            "promotionalDates": {
                "startDate": {
                    "Year": 2024,
                    "Month": 5,
                    "Day": 11
                },
                "endDate": {
                    "Year": 2024,
                    "Month": 5,
                    "Day": 18
                }
            }
        }
    ],
    "tag": [
        "#ShopLocal",
        "#FashionStore",
        "#SeasonalSale",
        "#FreeShipping",
        "#MembershipDeals"
    ]
}

예제 1: 문서의 배열 연결

이 쿼리는 배열의 categoryNamepromotionEvents.discounts 필드를 배열과 tag 단일 combinedTags 배열로 병합합니다.

db.stores.aggregate([{
    $match: {
        _id: "7954bd5c-9ac2-4c10-bb7a-2b79bd0963c5"
    }
}, {
    $project: {
        combinedTags: {
            $concatArrays: ["$promotionEvents.discounts.categoryName", "$tag"]
        }
    }
}])

이 쿼리는 다음 결과를 반환합니다.

[
  {
      "_id": "7954bd5c-9ac2-4c10-bb7a-2b79bd0963c5",
      "combinedTags": [ '#ShopLocal', '#NewArrival', '#NewArrival', '#FreeShipping' ]
  }
]