cursor.map() (original) (raw)

cursor.map(function)

Important

mongosh Method

This page documents a mongosh method. This is _not_the documentation for a language-specific driver, such as Node.js.

For MongoDB API drivers, refer to the language-specificMongoDB driver documentation.

Applies a function to each document visited by the cursor and collects the return values from successive applications of thefunction into a Cursor object.

The cursor.map() method has the following parameter:

Parameter Type Description
function function A function to apply to each document visited by the cursor.

This method is available in deployments hosted in the following environments:

Note

This command is supported in all MongoDB Atlas clusters. For information on Atlas support for all commands, seeUnsupported Commands.

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().

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 }

])

Get the product names.


db.products.find().map( function(p) { return p.name; } ) ;

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

See also: