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

如何在MongoDB中获取指定字段的纯数组形式输出?

获取MongoDB指定字段的纯数组输出

要将查询结果转换为taskIds字段的纯数组形式,可通过以下两种方式实现:

方式一:用Mongo Shell的map函数处理结果

执行基础查询后,通过map提取每个文档的taskIds数组:

db.users.find(
  { taskIds: { $in: [ObjectId("638764689c4ed1fbff18859a")] } },
  { taskIds: 1, _id: 0 }
).map(doc => doc.taskIds)[0]

输出结果:

[
  ObjectId("638764689c4ed1fbff18859a"),
  ObjectId("638764689c4ed1fbff18859c")
]

方式二:用聚合管道直接生成结果

通过聚合管道的$match、$project和$replaceRoot操作,直接将taskIds数组作为输出根文档:

db.users.aggregate([
  { $match: { taskIds: { $in: [ObjectId("638764689c4ed1fbff18859a")] } } },
  { $project: { _id: 0, taskIds: 1 } },
  { $replaceRoot: { newRoot: "$taskIds" } }
])

如果存在多个匹配文档,该命令会返回每个文档对应的taskIds数组;若需合并所有匹配的taskIds为一个去重数组,可使用以下聚合语句:

db.users.aggregate([
  { $match: { taskIds: { $in: [ObjectId("638764689c4ed1fbff18859a")] } } },
  { $unwind: "$taskIds" },
  { $group: { _id: null, taskIds: { $addToSet: "$taskIds" } } },
  { $project: { _id: 0 } }
])

内容的提问来源于stack exchange,提问作者Melih Özcan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 17:15:34