$concatArrays(数组表达式)
适用对象: MongoDB vCore
$concatArrays
运算符用于将多个文档合并为单个文档。 当需要合并不同文档中的数组或一个文档中的字段时,此运算符非常有用。
$concatArrays
运算符的语法如下所示:
{
"$concatArrays": [ "<array1>", "<array2>"]
}
说明 | |
---|---|
<array1>, <array2> |
用于串联的数组字段。 |
让我们了解 stores
数据集中的示例 json 的用法。
{
"_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"
]
}
示例管道将 categoryName
字段(promotionEvents.discounts
数组中的)与 tag
数组合并为单个 combinedTags 数组。
db.stores.aggregate([
{ $match: { _id: '7954bd5c-9ac2-4c10-bb7a-2b79bd0963c5' } }
,{ $project: { combinedTags: { $concatArrays: ["$promotionEvents.discounts.categoryName", "$tag"] } } }
])
该查询返回文档中合并为单个数组的数组 categoryName
和 tags
。
{
"_id": "7954bd5c-9ac2-4c10-bb7a-2b79bd0963c5",
"combinedTags": [
[ "DJ Turntables", "DJ Mixers" ],
"#ShopLocal",
"#FashionStore",
"#SeasonalSale",
"#FreeShipping",
"#MembershipDeals"
]
}