0

According to MongoDB manual, the below code exhausts the array and stores the the docs returned by the query to RAM:

var myCurse = db.coll.find();
var docs = myCurse.toArray()

If I type in the command :

myCurse.forEach(printjson);

after the first two commands, nothing is returned. So basically the cursor has been exhausted. All looks good here.

Now if do the below:

var myCurse = db.coll.find();
myCurse.toArray()[1];

and then:

myCurse.toArray()[2];

I still get results.

My questions are:

  1. does myCurse.toArray()[i]; where i is an index, implement an array underneath so that myCurse.toArray()[i]; can be utilized multiple times.
  2. How long do the documents get stored in RAM?
  3. What happens if size of returned documents exceeds RAM size?

Using MongoDB 3.2.8

1 Answer 1

1

Cursor.toArray() goes through the whole cursor, putting the results in to an array, until there are no more results. The cursor is now "expended" if you like, but the results is a completely normal array.

Those documents will be in RAM until garbage collection gets rid of it. In other words, at least as long as you keep a reference to the array or any of the entries in the array. After that, all bets are off. They may be removed quickly or they may stick around for a while, but it's generally not something to worry about.

I've never come across the scenario where the size of the returned documents exceed RAM size, but I expect page files will be used if available (and if the application is allowed to use that much RAM), and then finally there will be an exception as you run out of memory. If you need to deal with significant quantities of data in this way, don't use toArray() as it would be extremely inefficient anyway.

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

Comments

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.