I have an MongoDB collection with 100 records, in NodeJs I want retrieve as 10 records with each containing 10 records, how do I do that
Asked
Active
Viewed 129 times
0
-
Does order matter or perhaps some kind of way to group them? – ChaosPandion Mar 23 '19 at 23:18
-
Order doesn’t matter, just retrieve all and group without duplicates – veeRN Mar 23 '19 at 23:19
1 Answers
1
If you want the records to be distinct you can use the Set object to help with that. The function takes a function that gets the key of the item so we know how to differentiate them.
function groupByDistinct(records, groupSize, getKey) {
const set = new Set();
let result = [], current = [];
for (let i = 0, l = records.length; i < l; i++) {
const value = records[i], key = getKey(value);
if (set.has(key) {
continue;
}
set.add(key);
current.push(value);
if (current.length === groupSize) {
result.push(current);
current = [];
}
}
if (current.length !== 0) {
result.push(current);
}
return result;
}
Example Usage
groupByDistinct(records, 10, x => x.key);

ChaosPandion
- 77,506
- 18
- 119
- 157
-
-
@veeRN - Well I did assume you already had the data pulled. There must be a way to do it in MongoDB honestly. – ChaosPandion Mar 23 '19 at 23:30
-
Ok, the data could grow upto 30000 records, I don’t want to go thru 30000 records and group it by 10 or 100 , looking for some ways to have the data retrieved as set of 10’s or 100’s – veeRN Mar 23 '19 at 23:42
-
@veeRN - 30k is not too bad, 300k might be a problem. You would need some kind of windowing function to do this but I'm not familiar with everything available in MongoDB. We would both have to hit the docs. – ChaosPandion Mar 23 '19 at 23:43
-
@veeRN - I say give both a shot but who knows you might get a MongoDB pro shortly. – ChaosPandion Mar 23 '19 at 23:46