Database Manual / Reference / mongosh Methods / Cursors

cursor.map() (mongosh method方法)

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.本页记录了一种mongosh方法。这不是针对特定语言驱动程序(如Node.js)的文档。

For MongoDB API drivers, refer to the language-specific MongoDB driver documentation.有关MongoDB API驱动程序,请参阅特定语言的MongoDB驱动程序文档

Applies a function to each document visited by the cursor and collects the return values from successive applications of the function into a Cursor object.function应用于游标访问的每个文档,并将函数连续应用程序的返回值集合到游标对象中。

The cursor.map() method has the following parameter:cursor.map()方法有以下参数:

Parameter参数Type类型Description描述
functionfunctionA 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:云中MongoDB部署的完全托管服务

Note

This command is supported in all MongoDB Atlas clusters. 所有MongoDB Atlas集群都支持此命令。For information on Atlas support for all commands, see Unsupported Commands.有关Atlas支持所有命令的信息,请参阅不支持的命令

  • MongoDB Enterprise: The subscription-based, self-managed version of MongoDB:MongoDB的基于订阅的自我管理版本
  • MongoDB Community: The source-available, free-to-use, and self-managed version of MongoDB:MongoDB的源代码可用、免费使用和自我管理版本

Behavior行为

cursor.map() returns a Cursor object. 返回一个Cursor对象。Note that .map() only converts the type, it does not create a new cursor. 请注意,.map()只转换类型,它不会创建新的游标。You can convert the Cursor object to an Array with .toArray().您可以使用toArray()Cursor对象转换为Array

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 ArrayArray形式返回结果

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确认输出是Array

salePrices.constructor.name

Tip

cursor.forEach() for similar functionality.用于类似的功能。