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

使用JS编写MongoDB查询统计所有文档的唯一标签数量

使用JavaScript编写MongoDB查询统计唯一标签数量

文档结构示例

{
  "_id": { "$oid": "62e593aed8fd9808777225e8" },
  "title": "“The world as we have created it is a process of our thinking. It cannot be changed without changing our thinking.”",
  "author": {
    "name": "Albert Einstein",
    "url": "https://quotes.toscrape.com/author/Albert-Einstein"
  },
  "tag": ["change", "deep-thoughts", "thinking", "world"]
}

解决方案

以下提供两种高效的查询方式,适用于不同场景:

方法1:拆分标签后统计唯一总数(支持同时获取单个标签出现次数)

通过$unwind拆分标签数组,再用$group去重,最后$count统计分组数量:

// MongoDB Shell 执行代码
db.quotes.aggregate([
  // 将每个文档的tag数组拆分为单个文档
  { $unwind: "$tag" },
  // 按标签分组去重
  { $group: { _id: "$tag" } },
  // 统计唯一标签的总数
  { $count: "unique_tags_count" }
])

如果需要同时查看每个标签的出现次数,可修改$group阶段:

db.quotes.aggregate([
  { $unwind: "$tag" },
  { $group: { _id: "$tag", count: { $sum: 1 } } },
  { $count: "unique_tags_count" }
])

方法2:聚合收集唯一标签后统计长度(性能更优)

无需拆分所有文档,通过$addToSet收集所有唯一标签数组,再用$reduce拼接为一维数组,最后$size统计长度:

// MongoDB Shell 执行代码
db.quotes.aggregate([
  // 收集所有文档的tag数组到唯一集合中
  { $group: { _id: null, uniqueTags: { $addToSet: "$tag" } } },
  // 拼接数组并统计唯一标签总数
  { $project: {
    unique_tags_count: {
      $size: {
        $reduce: {
          input: "$uniqueTags",
          initialValue: [],
          in: { $concatArrays: ["$$value", "$$this"] }
        }
      }
    }
  } }
])

Node.js 驱动中使用示例

const { MongoClient } = require('mongodb');

async function countUniqueTags() {
  const client = new MongoClient('mongodb://localhost:27017');
  
  try {
    await client.connect();
    const db = client.db('your_db_name');
    const collection = db.collection('quotes');

    const [result] = await collection.aggregate([
      { $group: { _id: null, uniqueTags: { $addToSet: "$tag" } } },
      { $project: {
        unique_tags_count: {
          $size: {
            $reduce: {
              input: "$uniqueTags",
              initialValue: [],
              in: { $concatArrays: ["$$value", "$$this"] }
            }
          }
        }
      } }
    ]).toArray();

    console.log(`唯一标签总数:${result?.unique_tags_count || 0}`);
  } finally {
    await client.close();
  }
}

countUniqueTags().catch(console.error);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 16:45:47