You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

MongoDB数组过滤聚合:按标签分组统计无结果问题排查

Fixing Your MongoDB Aggregation Pipeline Issue

Hey there! Let's break down why your aggregation is returning 0 documents, and how to get the expected results.

The Root Problem: Pipeline Stage Order

MongoDB executes aggregation stages in the exact order you define them, and that's where your code went wrong. You first grouped all documents by their full tags array, then tried to match on a tags field—but after grouping, the output documents don't have a top-level tags field anymore!

Your original pipeline creates documents that look like this after the $group stage:

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

There's no tags field to match against, so the subsequent $match stage finds zero matches.

The Corrected Pipeline

You need to filter first, then group. Here's the fixed code:

client.db('mydb').collection('Files').aggregate([
  // Step 1: Filter documents that include the 'video' tag
  { $match: { tags: 'video' } },
  // Step 2: Group by the full tags array and count occurrences
  { $group: { _id: '$tags', total: { $sum: 1 } } }
]).toArray()

How This Works

  1. $match First: This stage filters out all documents where the tags array doesn't include 'video'. From your sample data, this leaves 3 documents:
    • {tags: ['video', 'Alex'], ... }
    • {tags: ['video', 'John'], ... }
    • {tags: ['video', 'John'], ... }
  2. $group Second: Now we group these filtered documents by their full tags array. This gives you exactly the expected result:
    [
      { _id: ['video', 'Alex'], total: 1 },
      { _id: ['video', 'John'], total: 2 }
    ]
    

Quick Note on Matching Array Elements

MongoDB's default behavior for { tags: 'video' } is to match any document where the tags array contains 'video'—which is exactly what you need here, so no need for extra operators like $elemMatch or $in in this case.

内容的提问来源于stack exchange,提问作者Alexey Sviridov

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.09 14:12:32