【问题标题】:searching list of objects by key and returning count按键搜索对象列表并返回计数
【发布时间】: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


    【解决方案1】:

    有多种方法可以做到这一点,但基本逻辑是执行 groupBy 并与查找表匹配。使用lodash 或辅助库会更容易。而且不使用JS也可以很容易地完成。

    你可以使用这个快速解决方案:

    //Group by type and then storing the count
    const grouped = allObs.reduce((p, c) => {
        p[c.type] = p[c.type] || 0;
        p[c.type] += 1;
        return p;
    }, {});
    
    // putting that into a result array.
    const result = lookupTable
        .filter(entry=>grouped[entry._id]) //filtering whatever is not there
        .map(entry => {
            return { name: entry.type, data: [grouped[entry._id]] }
        });
    

    您可以使用旧的 for 循环一次完成。

    输出:

    [ { name: 'duck', data: [ 2 ] }, { name: 'crane', data: [ 1 ] } ]
    

    【讨论】:

    • 谢谢!如果你想添加一个例子,lodash 是公平的游戏。
    猜你喜欢
    • 2012-01-15
    • 2021-07-23
    • 2015-07-06
    • 1970-01-01
    • 2013-03-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多