MongoDB map()

In MongoDB, the cursor.map() method applies a function to each document visited by the cursor and combines the return values in an array.

Syntax

The syntax goes like this:

db.collection.find().map(<function>)

Where collection is the name of the collection that the documents reside in.

And where <function> is the function to apply to each document visited by the cursor.

Example

Suppose we have a collection called products that contains the following three documents:

{ "_id" : 1, "product" : "Left Handed Screwdriver" }
{ "_id" : 2, "product" : "Left Blinker" }
{ "_id" : 3, "product" : "Long Weight" }

We can use the map() method in conjunction with the find() method to iterate through those documents, while applying a function to each document.

Example:

db.products.find().map(
  function(p) {
    p = p.product.replace("Left","Right");
    return p;
  }
);

Result:

[ "Right Handed Screwdriver", "Right Blinker", "Long Weight" ]

In this case, we iterated through the cursor, and replaced instances of the string Left with Right. We then returned the result.

The result is returned as an array.

Error?

If you get an error, like this:

uncaught exception: TypeError: db.products.findOne(...).map is not a function :
@(shell):1:1

Be sure that you’re using find() and not findOne().

The findOne() method returns the actual document and not a cursor. Therefore, map() won’t work with findOne(). Also, even if it did work, findOne() only returns a single document, and therefore, there would be no need to iterate through multiple documents.