【发布时间】:2021-09-16 08:21:44
【问题描述】:
我正在使用带有 Node API 的 MongoDB,并且一个路由需要返回集合中每种类型的汇总计数。
我没有使用 MongoDB Aggregate 管道,因为我需要的数据已经发送到 API 以获取同一路由中的其他汇总统计信息。
注意:为了便于使用,我将下面的 _id 放在单引号中,但它们是 mongoose.Schema.Types.ObjectId 的。
所以,假设我有一个这样的 mongo 对象数组:
const allObs = [
{
_id: '60d5f37fd93fb82ebe84d920',
type: '60d5f1d4cdc8942dc5b6b12e',
otherFields: 'about 10 - removed for clarity'
},
{
_id: '60d5f389d93fb82ebe84d926',
type: '60d5f1d4cdc8942dc5b6b12e',
otherFields: 'ditto'
},
{
_id: '60d5f39bd93fb82ebe84d92c',
type: '60d5f1e3cdc8942dc5b6b138',
otherFields: 'foobarbarfoo'
}
]
我有一个这样的查找表...
const lookupTable = [
{ _id: '60d5f1d4cdc8942dc5b6b12e', type: 'duck' },
{ _id: '60d5f1decdc8942dc5b6b133', type: 'goose' },
{ _id: '60d5f1e3cdc8942dc5b6b138', type: 'crane' },
{ _id: '60d5f1e9cdc8942dc5b6b13d', type: 'heron' }
]
如何创建这样的汇总表?
[
{ name: 'duck', data: [2] },
{ name: 'crane', data: [1] }
]
生成的表结构有点奇怪(具有单值数组的数据),但我们需要 Apex 图表的这种结构。
任何帮助都会很棒,谢谢。
【问题讨论】:
标签: javascript node.js arrays mongodb mongoose