Hi. I am trying to retrieve total count of docs as well as paginated docs. Is there a way to retrieve everything in one request?
I want to be sure that the total count of docs is the same as paginated docs when someone just removed the doc.
The problem:
I am querying total count - I get 5. Just some ms later I fetch for paginated results
Meanwhile someone deletes the fifth document - the total count is 5 but there are only 4 documents.
Can I solve this with cursor or the only option is to use aggregation?
Hi @Proth7_N_A and welcome in the MongoDB Community !
I think I would wrap the entire thing in a read multi-doc transaction or the aggregation pipeline for a single command but it really depends how you organise it really.
You could also send a count(x)
command + your paginated find(x)
each time you update the view. I think the users wouldn’t be surprised if the count changed when they click on <page 2> as they know it’s a multi users page.
Cheers,
Maxime.
Alternatively, you may use $facet, one to get the total count and the second one to get the current page.
However, I can conquer with Maxime, that most are not surprise if total count change, if inventory level change between clicks.
Even if you do 2 requests, with 5 total count and get only 4 docs, there is nothing that stops you from adjusting your 5 total count to 4 if only 4 docs show up.
I am pretty sure that is why some came up with the infinite scroll which I hate as a user. I rather have some kind of an idea of where I am. With infinite scroll it looks like there is always more then my FOMO kicks in.
Thanks Maxime. I wiill take a look intro multi-doc transaction as well as possible aggregation pipeline for it
I see. Thanks for setting up few ideas in my mind