Calling .find() twice with filters vs using .fetch().filter()


I have a collection of Messages and am trying to pull some of their contents based on their status of isRead and isUrgent so that I can have 2 arrays (they do not need to be reactive):

  1. unreadUrgentMessages
  2. unreadNotUrgentMessages

Is it better to:

A) call Messages.find() twice on the collection with the filters inside the .find, e.g. Messages.find({isRead: false, isUrgent: true}).map(...) and Messages.find({isRead: false, isUrgent: false}).map(...)


B) call Messages.find({isRead: false}).fetch() and then use .filter(...).map(...) on the array?

B feels a little more efficient but I’m not sure. Or is there a more optimal approach?


If there aren’t many messages in the collection, I wouldn’t really worry about it. That said:

(A) will make 2 database queries rather than one, but it has the advantage of not loading all of the query results into memory at the same time. However, it will allocate memory for the array returned by the map functions which will likely be comparable in size to the query results, if not bigger.

(B) only makes 1 db query but will load all messages into memory at the same time. Also, calling the filter before the map will allocate another temporary array in addition to the arrays allocated by fetch and map.

It probably doesn’t make much of a difference, but the more efficient thing to do would be to call Messages.find({ isRead: false }).forEach and manually construct whatever arrays you want inside of the forEach callback.

1 Like