MongoDB查询结果转换:将find结果精简为ObjectId数组
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

