0

I'm using Mongoose in nodejs. So here is a sample Publisher model:

name: String,
books: [{
    title: String,
    author: {
        name: String,
        age: Number
    }
}]

I want to get all the distinct author names that match a regex. I'm new to noSql so maybe I'm just doing something dumb. I figure I want to do something like:

Publisher.aggregate([
    {$unwind: '$books'},
    {$match: {
        'books.author.name': new RegExp(req.params.regex)
    }},
    {$group: {
        _id: '$books.author.name'
    }},
    {$group: {
        distinctValues: {$addToSet: '$_id'}
    }}
], function(err, result) {
    if(err) throw err;
    res.json(result);
})

This seems like it should work according to: https://dba.stackexchange.com/questions/59661/mongodb-distinct-in-an-array

Any and all input you guys have to help me with this would be much appreciated.

1 Answer 1

2

You didnt provide an error you get when performing this query, but it seems you get something like: 'a group specification must include an _id'. The issue with your query is here:

{$group: {
    distinctValues: {$addToSet: '$_id'}
}}

$group operator MUST include an _id field

So far $group operator provides already distinct group this last pipeline seems redundant, next works for me:

Publisher.aggregate([
    {$unwind: '$books'},
    {$match: {
        'books.author.name': new RegExp(req.params.regex)
    }},
    {$group: {
        _id: '$books.author.name'
    }}
], function(err, result) {
    if(err) throw err;
    res.json(result);
})
Sign up to request clarification or add additional context in comments.

2 Comments

That works. Thanks. I'm confused though. The values returned seem to be distinct but your change does not specify any requirement on uniqueness. Why is that?
Thats how $group operator works, you can check the documentation, they have general examples up there (docs.mongodb.com/manual/reference/operator/aggregation/group). From the docs: 'Groups documents by some specified expression and outputs to the next stage a document for each distinct grouping'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.