5

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));

1 Answer 1

10

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.

Sign up to request clarification or add additional context in comments.

2 Comments

A comment on performance difference would be nice.
@Bartleby I don't think it's possible to give a generic comment on performance: it depends on the hardware MongoDB is running on, the hardware on which the application is running, the amount of records (and their size) being transferred, the specific mapping being performed, etc.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.