【问题标题】:MongoDB extract subdocument array values from multiple documentsMongoDB 从多个文档中提取子文档数组值
【发布时间】:2021-06-26 01:55:16
【问题描述】:

我正在使用 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
}

如何删除“更新”并获取实际对象?

【问题讨论】:

标签: database mongodb mongodb-query time-series aggregation-framework


【解决方案1】:

演示 - https://mongoplayground.net/p/Dw7NAn9EoEd

使用$replaceRoot

db.collection.aggregate([
  { $match: { marketId: marketId } },
  { $project: { _id: 0, updates: 1 }},
  { $unwind: "$updates" },
  { $replaceRoot: { newRoot: "$updates" } }
])

【讨论】:

  • 这行得通!结果我忘了使用 [] 符号来列出聚合,所以它没有正确执行。 ReplaceRoot 完美运行。谢谢你 Tushar :)
猜你喜欢
  • 2016-02-01
  • 2015-02-18
  • 2021-11-18
  • 2023-03-28
  • 1970-01-01
  • 2018-01-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多