运算符 $mergeObjects
将多个文档合并到单个文档中。 mergeObjects作用于聚合管道,以合并来自不同文档的字段或向现有文档添加一个或多个字段。 当发生冲突时,运算符用源文档中的字段覆盖目标文档中的字段。
语法
{
$mergeObjects: [ < document1 > , < document2 > , ...]
}
parameters
参数 | 说明 |
---|---|
document1, document2 |
要合并的文档。 可以将文档指定为字段路径、子文档或常量。 |
例子
让我们了解 stores
数据集中的示例 json 的用法。
{
"_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4",
"name": "First Up Consultants | Beverage Shop - Satterfieldmouth",
"location": {
"lat": -89.2384,
"lon": -46.4012
},
"staff": {
"totalStaff": {
"fullTime": 8,
"partTime": 20
}
},
"sales": {
"totalSales": 75670,
"salesByCategory": [
{
"categoryName": "Wine Accessories",
"totalSales": 34440
},
{
"categoryName": "Bitters",
"totalSales": 39496
},
{
"categoryName": "Rum",
"totalSales": 1734
}
]
},
"promotionEvents": [
{
"eventName": "Unbeatable Bargain Bash",
"promotionalDates": {
"startDate": {
"Year": 2024,
"Month": 6,
"Day": 23
},
"endDate": {
"Year": 2024,
"Month": 7,
"Day": 2
}
},
"discounts": [
{
"categoryName": "Whiskey",
"discountPercentage": 7
},
{
"categoryName": "Bitters",
"discountPercentage": 15
},
{
"categoryName": "Brandy",
"discountPercentage": 8
},
{
"categoryName": "Sports Drinks",
"discountPercentage": 22
},
{
"categoryName": "Vodka",
"discountPercentage": 19
}
]
},
{
"eventName": "Steal of a Deal Days",
"promotionalDates": {
"startDate": {
"Year": 2024,
"Month": 9,
"Day": 21
},
"endDate": {
"Year": 2024,
"Month": 9,
"Day": 29
}
},
"discounts": [
{
"categoryName": "Organic Wine",
"discountPercentage": 19
},
{
"categoryName": "White Wine",
"discountPercentage": 20
},
{
"categoryName": "Sparkling Wine",
"discountPercentage": 19
},
{
"categoryName": "Whiskey",
"discountPercentage": 17
},
{
"categoryName": "Vodka",
"discountPercentage": 23
}
]
}
]
}
示例 1 - 将文档合并为按销售子文档分组的累加器
查询是一个聚合管道,它使用$mergeObjects合并特定公司每个城市的所有销售子文档。
db.stores.aggregate([
{
$match: {
company: "Fourth Coffee"
}
},
{
$group: {
_id: "$city",
mergedSales: {
$mergeObjects: "$sales"
}
}
},
{
$limit: 2 // returns only the first 3 grouped cities
}
])
查询按城市存储公司“Fourth Coffee”的文档,并将其销售字段合并到每个城市的单个对象中。
[
{
"_id": "Jalonborough",
"mergedSales": {
"totalSales": 45747,
"salesByCategory": [
{
"categoryName": "Bucket Bags",
"totalSales": 45747
}
]
}
},
{
"_id": "Port Vladimir",
"mergedSales": {
"totalSales": 32000,
"salesByCategory": [
{
"categoryName": "DJ Speakers",
"totalSales": 24989
},
{
"categoryName": "DJ Cables",
"totalSales": 7011
}
]
}
}
]
相关内容
- 查看有关 从 MongoDB 迁移到适用于 MongoDB 的 Azure Cosmos DB (vCore) 的选项。
- 详细了解 与 MongoDB 的功能兼容性。