-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
cursor.map.txt
87 lines (54 loc) · 1.87 KB
/
cursor.map.txt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
============
cursor.map()
============
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
.. method:: cursor.map(function)
.. include:: /includes/fact-mongosh-shell-method.rst
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.
The :method:`cursor.map()` method has the following parameter:
.. list-table::
:header-rows: 1
:widths: 20 20 80
* - Parameter
- Type
- Description
* - ``function``
- function
- A function to apply to each document visited by the cursor.
Behavior
--------
:method:`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:
.. code-block:: javascript
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.
.. code-block:: javascript
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.
.. code-block:: javascript
var salePrices = db.products.find().map( function(p) { return p.price * .9 } ).toArray() ;
Confirm that the output is an ``Array``
.. code-block:: javascript
salePrices.constructor.name
.. seealso::
:method:`cursor.forEach()` for similar functionality.