Docs 菜单
Docs 主页
/
MongoDB Manual
/ / /

cursor.map()

在此页面上

  • 行为
  • 举例
cursor.map(function)

重要

mongosh 方法

本页面提供 mongosh 方法的相关信息。这不是特定于语言的驱动程序(例如 Node.js)的文档。

如需了解 MongoDB API 驱动程序,请参阅特定语言的 MongoDB 驱动程序文档。

function 应用到游标访问的每个文档,并从 function 的连续应用中收集返回值到 Cursor 对象中。

cursor.map() 方法具有以下参数:

Parameter
类型
说明
function
function
应用于游标访问的每个文档的函数。

cursor.map() 返回一个 Cursor 对象。请注意,.map() 只转换类型,并不创建新游标。您可以用 .toArray()Cursor 对象转换为 Array

以下示例涉及产品集合:

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 }
])

获取产品名称。

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

计算折扣销售价格,然后将结果作为数组返回。

var salePrices = db.products.find().map( function(p) { return p.price * .9 } ).toArray() ;

确认输出是 Array

salePrices.constructor.name

提示

另请参阅:

cursor.forEach() 对于类似功能。

后退

cursor.limit

在此页面上