cursor.map(function)Important
mongosh Method
This is a
mongoshmethod. This is not the documentation forNode.jsor other programming language specific driver methods.In most cases,
mongoshmethods work the same way as the legacymongoshell methods. However, some legacy methods are unavailable inmongosh.For the legacy
mongoshell documentation, refer to the documentation for the corresponding MongoDB Server release:For MongoDB API drivers, refer to the language specific MongoDB driver documentation.
Applies a
functionto each document visited by the cursor and collects the return values from successive applications of thefunctioninto aCursorobject.The
cursor.map()method has the following parameter:ParameterTypeDescriptionfunctionfunction
A function to apply to each document visited by the cursor.
Compatibility
This method is available in deployments hosted in the following environments:
MongoDB Atlas: The fully managed service for MongoDB deployments in the cloud
Note
This command is supported in all MongoDB Atlas clusters. For information on Atlas support for all commands, see Unsupported Commands.
MongoDB Enterprise: The subscription-based, self-managed version of MongoDB
MongoDB Community: The source-available, free-to-use, and self-managed version of MongoDB
Behavior
cursor.map() returns a Cursor object. Note that
.map() only converts the type, it does not create a new cursor. You
can convert the Cursor object to an Array with .toArray().
Examples
These examples refer to the products collection:
db.products.insertMany([ { _id: 1, name: 'widget', price: 10.89 }, { _id: 2, name: 'thing', price: 11.24 }, { _id: 3, name: 'moppet', price: 8 }, { _id: 4, name: 'cosa', price: 24.19 } ])
Return a Value From a Collection
Get the product names.
db.products.find().map( function(p) { return p.name; } ) ;
Return Results as an Array
Calculate a discounted sale price and return the results as an array.
var salePrices = db.products.find().map( function(p) { return p.price * .9 } ).toArray() ;
Confirm that the output is an Array
salePrices.constructor.name
Tip
cursor.forEach() for similar functionality.