【发布时间】:2021-07-13 11:23:25
【问题描述】:
我在 MongoDB Atlas 上有一个 MongodDB 数据库。
它有“orders”、“products”、“itemTypes”和“brands”。
- “orders”仅跟踪订购的产品 ID。
- “products”只记录品牌 id 和 itemType id
- “itemTypes”跟踪项目类型名称
- “brands”跟踪品牌名称。
如果我汇总订单 + 产品 + itemTypes 就可以了:
[{
$unwind: {
path: '$orders'
}
}, {
$lookup: {
from: 'products',
localField: 'orders.productId',
foreignField: 'productId',
as: 'products'
}
}, {
$lookup: {
from: 'itemTypes',
localField: 'products.typeId',
foreignField: 'typeId',
as: 'itemTypes'
}
}, {
$set: {
'orders.price': {
$arrayElemAt: ['$products.price', 0]
},
'orders.brandId': {
$arrayElemAt: ['$products.brandId', 0]
},
'orders.typeId': {
$arrayElemAt: ['$products.typeId', 0]
},
'orders.typeName': {
$arrayElemAt: ['$itemTypes.name', 0]
}
}
}, {
$group: {
_id: '$_id',
createdAt: {
$first: '$createdAt'
},
status: {
$first: '$status'
},
retailerId: {
$first: '$retailerId'
},
retailerName: {
$first: '$retailerName'
},
orderId: {
$first: '$orderId'
},
orders: {
$push: '$orders'
}
}
}]
如果我聚合订单 + 产品 + itemTypes + 品牌,无论是 Mongo Compass 还是 Mongo Atlas 聚合构建器的 Web UI 都会出现操作超时错误。
[{
$unwind: {
path: '$orders'
}
}, {
$lookup: {
from: 'products',
localField: 'orders.productId',
foreignField: 'productId',
as: 'products'
}
}, {
$lookup: {
from: 'itemTypes',
localField: 'products.typeId',
foreignField: 'typeId',
as: 'itemTypes'
}
}, {
$lookup: {
from: 'brands',
localField: 'products.brandId',
foreignField: 'brandId',
as: 'brands'
}
}, {
$set: {
'orders.price': {
$arrayElemAt: ['$products.price', 0]
},
'orders.brandId': {
$arrayElemAt: ['$products.brandId', 0]
},
'orders.typeId': {
$arrayElemAt: ['$products.typeId', 0]
},
'orders.typeName': {
$arrayElemAt: ['$itemTypes.name', 0]
},
'orders.brandName': {
$arrayElemAt: ['$brands.name', 0]
}
}
}, {
$group: {
_id: '$_id',
createdAt: {
$first: '$createdAt'
},
status: {
$first: '$status'
},
retailerId: {
$first: '$retailerId'
},
retailerName: {
$first: '$retailerName'
},
orderId: {
$first: '$orderId'
},
orders: {
$push: '$orders'
}
}
}]
这是一个超时聚合的演示:
https://mongoplayground.net/p/Jj6EhSl58MS
我们有大约 5 万个订单、1.4 万种产品、200 个品牌、89 种商品类型。
有没有办法优化这个聚合使其不会超时?
P/s:我的最终目标是使用 Mongodb Charts 功能中的漂亮图表可视化流行品牌和订购的商品类型。
【问题讨论】:
标签: mongodb aggregation mongodb-atlas