【问题标题】:MongoDB agregation with filtering in array具有数组过滤功能的 MongoDB 聚合
【发布时间】:2020-10-09 20:56:48
【问题描述】:

我需要对按标签分组的记录进行计数,并在包括 in 个之前进行过滤

// in db
{tags: ['video', 'Alex'], ... },
{tags: ['video', 'John'], ... },
{tags: ['video', 'John'], ... },
{tags: ['text', 'Alex'], ... },
{tags: ['text', 'John'], ... },


client.db('mydb').collection('Files').aggregate(
        [
          { $group: { _id: { tags: '$tags' }, total: { $sum: 1 } } },
          { $match: { tags: 'video' } },
        ],
      ).toArray()

但遗憾的是,我得到了零个文档。如果删除 $group 部分,我会得到 3 个文档。 在最初的请求中,我预计有 2 个文档

{ _id: ['video', 'Alex'], total: 1 },
{ _id: ['video', 'John'], total: 2 }

【问题讨论】:

    标签: javascript node.js mongodb typescript


    【解决方案1】:

    在聚合中,管道的顺序很重要,因为前一阶段的输出被馈送到下一个阶段。

    您的查询几乎与预期输出有关。只需将$match 阶段移动到$group 阶段之前。

    查询:

    db.collection.aggregate([
      {
        $match: {
          "tags": "video"
        }
      },
      {
        $group: {
          _id: {
            tags: "$tags"
          },
          total: {
            $sum: 1
          }
        }
      }
    ]);
    

    Working Example

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-05-09
      • 2016-05-03
      • 1970-01-01
      • 1970-01-01
      • 2021-12-13
      • 1970-01-01
      • 1970-01-01
      • 2021-07-26
      相关资源
      最近更新 更多