cursor.map()
On this page本页内容
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-specific MongoDB driver documentation.
Applies a将function
to each document visited by the cursor and collects the return values from successive applications of thefunction
into aCursor
object.function
应用于游标访问的每个文档,并将function
的连续应用程序的返回值集合到Cursor
对象中。Thecursor.map()
method has the following parameter:cursor.map()
方法具有以下参数:Parameter参数Type类型Description描述function
function A function to apply to each document visited by the cursor.应用于游标访问的每个文档的函数。
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 Array
以Array
形式返回结果
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
Array
salePrices.constructor.name
See also: 另请参阅:
cursor.forEach()
for similar functionality.用于类似的功能。