w3resource

MongoDB: cursor.map() method

cursor.map

The cursor.map() method is used to apply a function to each document by a cursor and collects the return values from successive application into in an array.

Syntax:

cursor.map()

Parameters:

Name Description Required /
Optional
Type
function A function to apply to each document visited by the cursor. Required function

Sample document in the restaurants collection:


{
  "address": {
     "building": "1007",
     "coord": [ -73.856077, 40.848447 ],
     "street": "Morris Park Ave",
     "zipcode": "10462"
  },
  "borough": "Bronx",
  "cuisine": "Bakery",
  "grades": [
     { "date": { "$date": 1393804800000 }, "grade": "A", "score": 2 },
     { "date": { "$date": 1378857600000 }, "grade": "A", "score": 6 },
     { "date": { "$date": 1358985600000 }, "grade": "A", "score": 10 },
     { "date": { "$date": 1322006400000 }, "grade": "A", "score": 9 },
     { "date": { "$date": 1299715200000 }, "grade": "B", "score": 14 }
  ],
  "name": "Morris Park Bake Shop",
  "restaurant_id": "30075445"
}
......

Example: MongoDB: cursor.map() method

The following example will retrieve all the documents from the collection restaurants which matches the query criteria cuisine is Indian and collect the return value into an array.

db.restaurants.find({cuisine : "Indian"}).map( function(u) { return u.cuisine; } );

Output:

> db.restaurants.find({cuisine : "Indian"}).map( function(u) { return u.cuisine; } );
[
        "Indian",
        "Indian",
        "Indian",
        "Indian",
        "Indian",
        "Indian",
        "Indian",
        "Indian",
        "Indian",
        "Indian",
        "Indian",
        "Indian",
        "Indian",
        "Indian",
        "Indian",
        "Indian",
        "Indian",
        "Indian",
        "Indian",
        "Indian",
        "Indian",
        "Indian",
        "Indian",
        "Indian",
        "Indian",
        "Indian",
        "Indian",
		...
]		

Retrieve the restaurants data from here

Previous: cursor.limit() method
Next: cursor.maxTimeMS() method



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/mongodb/shell-methods/cursor/cursor-map.php