Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

cursor.map().toArray() vs. cursor.toArray().then(array => array.map())

Is there a difference between these queries? I'm curious to know how mongo interprets javascript code passed to the map method vs. mapping once the query resolves.

db.collection('myCollection').find()
.map(document => document.value + 3)
.toArray();

vs.

db.collection('myCollection').find()
.toArray()
.then(array => array.map(document => document.value + 3));
like image 827
seven11 Avatar asked May 04 '16 10:05

seven11


People also ask

What is toArray method in Javascript?

The toArray() method returns the elements matched by the jQuery selector as an array.

What is toArray in Mongodb?

The toArray() method returns an array that contains all the documents from a cursor. The method iterates completely the cursor, loading all the documents into RAM and exhausting the cursor.


1 Answers

The first example will perform the mapping within the context of the MongoDB server (which has a built-in JS runtime), the second example will perform it locally, in your Node process.

The location of .toArray() is the key: it will exhaust the cursor, or in other words, it will transfer the set of result documents from the server to the client.

So cursor.toArray().map() will first transfer all the documents to the client, and the mapping will occur there, and cursor.map().toArray() will perform the mapping on each document on the server, and then transfer all documents to the client.

like image 176
robertklep Avatar answered Sep 28 '22 11:09

robertklep