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));
The toArray() method returns the elements matched by the jQuery selector as an array.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With