我正在使用 Bucket Pattern 划分市场更新的时间序列并避免超过文档大小(传输开销不是问题)。每个文档都有 30,000 个更新,我需要从数组中匹配“marketId”的所有文档返回这些更新(希望已排序)。
数据:
{
_id: 60617172eca858909eace71f,
marketId: '1.278363651',
eventId: 5697224,
marketType: 'OVER_UNDER_15',
size: 30000,
updates: [
{
t: 1616998770482.0,
p: 36.49
},
{
t: 1616998770482,
p: 87.77
},
// ... 29998 more
]
},
期望的结果:
[
{ t: 1616998770482, p: 36.49 },
{ t: 1616998770482, p: 16.59 },
{ t: 1616998770482, p: 40.38 },
... // sorted by t
}
这是我最接近的聚合尝试:
const result = await db.collection('markets').aggregate(
{ $match: { marketId: marketId } },
{ $project: { _id: 0, updates: 1 } },
{ $unwind: "$updates" },
{ $unwind: "$updates" },
).toArray();
输出:
[
{ updates: { t: 1616998770482, p: 36.49 } },
{ updates: { t: 1616998770482, p: 16.59 } },
{ updates: { t: 1616998770482, p: 40.38 } },
... // actually gives me all of them
}
如何删除“更新”并获取实际对象?
最佳答案
演示 - https://mongoplayground.net/p/Dw7NAn9EoEd
db.collection.aggregate([
{ $match: { marketId: marketId } },
{ $project: { _id: 0, updates: 1 }},
{ $unwind: "$updates" },
{ $replaceRoot: { newRoot: "$updates" } }
])
关于database - MongoDB 从多个文档中提取子文档数组值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66864335/