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

MongoDB查询结果转换:将find结果精简为ObjectId数组

Extract ObjectIds as an Array from MongoDB Query Results

Hey there! To convert your query results into an array containing only the ObjectIds, you can use one of these straightforward approaches:

Using Cursor.map() (Client-Side Transformation)

The find() method returns a cursor, which has a built-in map() function to transform each document. This is simple and works well for most cases:

// Get array of ObjectId instances
db.abhishek.em.find({}).map(doc => doc._id)

If you're using an older MongoDB shell version that doesn't support arrow functions, use the traditional function syntax:

db.abhishek.em.find({}).map(function(doc) {
  return doc._id;
})

Output Example:

[ObjectId("5ac62d35b075e574b3e7eeaa"), ObjectId("5ac62d3fb075e574b3e7eeab"), ObjectId("5ac62d4eb075e574b3e7eeac")]

If you need the string representations of the ObjectIds instead, modify the map function:

db.abhishek.em.find({}).map(doc => doc._id.toString())

String Output Example:

["5ac62d35b075e574b3e7eeaa", "5ac62d3fb075e574b3e7eeab", "5ac62d4eb075e574b3e7eeac"]

Using Aggregation (Database-Side Transformation)

For larger datasets, processing the transformation on the database server can reduce data transfer to the client. Use the aggregation pipeline:

db.abhishek.em.aggregate([
  { $project: { _id: 1 } }, // Keep only the _id field
  { $group: { _id: null, ids: { $push: "$_id" } } }, // Collect all _ids into an array
  { $project: { _id: 0, ids: 1 } } // Return just the ids array
]).toArray()[0].ids

This will give you the same array of ObjectIds as the cursor.map() method, but the work happens on the database side.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 08:07:07