Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

group by equivalent? #54

Open
headfox23 opened this issue Aug 31, 2016 · 1 comment
Open

group by equivalent? #54

headfox23 opened this issue Aug 31, 2016 · 1 comment

Comments

@headfox23
Copy link

Hey ho,
is there a way to do a classical group by as known in normal transactional databases?

I mean e.g. i have multiple entries with a field category. Now i want to have a list of categories...

Of course i can do the deduplication after the query... but it would be nice if the DB could handle this....
Currently i do this:

function getCategoriesFromDB(callback)
{
    DBStuff.find({}).filter(function(x){ return x.category != null }).map(function(x){ return { category: x.category } }).exec(function(err,categories) { 
        if(err != null)
        {
            callback(err,null);
        }
        if(categories == null)
        {
            callback(err,"no categories found");
        }

        //deduplication...
        function hash(o){
            return o.category;
        }    

        var hashesFound = {};

        categories.forEach(function(o){
            hashesFound[hash(o)] = o;
        })

        var uniqueCategories = Object.keys(hashesFound).map(function(k){
            return hashesFound[k];
        })
        //deduplication finished
        callback(err,uniqueCategories);
    });
}
@Ivshti
Copy link
Owner

Ivshti commented Aug 31, 2016

You can use .reduce() to do it, example:

.reduce(function(cur, obj) {
    cur[obj.category] = cur[obj.category] || [];
    cur[obj.category].push(obj);
}, { })

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants