Historically, I have used the following function on my backend to grab a paginated set of data from a given collection in my DB.
The count()
function on the cursor always used to give me the total number of documents that matched the query regardless of the skip
and limit
options, but now it seems like I’m only getting back the post-limit count.
const getData = (collection, options = {}) => {
let query = options.query || {}
if (options.searchTerm && options.searchFields) {
if (!query['$or']) {
query['$or'] = []
}
options.searchFields.map(field => {
query['$or'].push(
{ [field]: { $regex: options.searchTerm, $options: 'i' } },
)
})
}
let cleanup = {
limit: options.perPage,
skip: (options.page - 1) * options.perPage,
sort: {
[options.sortBy]: options.sortDirection === 'asc' ? 1 : -1
}
}
if (isNull(options.perPage)) {
cleanup = { sort: { [options.sortBy]: options.sortDirection === 'asc' ? 1 : -1 } }
}
let data = collection.find(query, cleanup)
return {
results: data.fetch(),
total: data.count()
}
}
I saw in the mongo docs:
MongoDB drivers compatible with the 4.0 features deprecate their respective cursor and collection
count()
APIs in favor of new APIs that corresponds tocountDocuments()
andestimatedDocumentCount()
. For the specific API names for a given driver, see the driver API documentation.
However countDocuments()
says “not a function” when I try to use it.
The docs also mention some applySkipLimit
option for count
which seems like maybe it should help but there are no examples of how it is used and none of my attempts have been successful.
At this point, the only solution I’ve been able to get to work is to effectively query the database twice like so:
let data = collection.find(query, cleanup).fetch()
let count = collection.find(query).count()
return {
results: data,
total: count
}
though I have to imagine this is not as performant and not my ideal solution.
Count is something that I use pretty extensively in many of my projects.
As I was wrapping this post up I noticed that the following was mentioned in the Meteor 2.6 Mongo notes:
applySkipLimit option for count() on find cursors is no longer supported.
Can anyone suggest any easy alternative to my existing use of count or speak to whether or not I’m going to see performance issues from effectively doubling up any queries that use it in conjunction with limit or skip?