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

如何使MongoDB聚合查询返回纯数组形式的结果?

解决方案

方法一:使用distinct()方法(最简便)

如果需求仅为获取集合中不重复的category值,直接调用distinct方法即可得到纯数组结果:

db.collection.distinct("category")

执行结果:

["Enhancement", "Bug"]

方法二:调整聚合管道(若必须使用聚合)

MongoDB聚合管道的输出始终是文档数组,无法直接返回纯数组,但可以调整管道简化结果,再通过客户端代码提取目标数组:

调整后的聚合查询:

db.collection.aggregate([
  {
    $group: {
      _id: null,
      categories: { $addToSet: "$category" }
    }
  },
  { $project: { _id: 0 } }
])

查询结果:

[
  {
    "categories": [
      "Enhancement",
      "Bug"
    ]
  }
]

之后在客户端提取数组(以Node.js为例):

const aggResult = await db.collection.aggregate([...]).toArray();
const pureArray = aggResult[0].categories;

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 19:20:18