database - MongoDB 从多个文档中提取子文档数组值

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

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

使用$replaceRoot

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/

相关文章:

java - 解释 mongostat 中的 mongo 故障指标

mongodb - 如何检索 MongoDB 上每个其他不同字段的字段最大的文档?

mysql - 用于在连续字符串中搜索的 SQL 查询

php - 如何用php管理cookies

java - 在文档中搜索值 [MongoDB]

mongodb - 从 mongodb 文档 _id 字段获取日期和时间

go - 如何在json中按深层排序在mongo中获取20个文档?

javascript - 当连接到 MongoDB Replicaset 时,Node.js "auth fail"仅 3 个服务器中的 2 个处于运行状态

mysql - 需要MySQL查询多对多映射计数记录

mysql - 不要重复两个不同表中的条目行