I am using Mongoose in a MEAN environment. How can I make sure to not have any duplicate results in my result set? Example: my database contains 10 (partly duplicate) names:
When querying this database for 'Allan' or maybe even just 'all' (using .find(regex...) and limiting the number of returned results to 5, I get this:
Having three duplicate entries of 'Allan', we waste a lot of result-diversity (talking about an autocomplete function for a search input field). I need the returned result set free of duplicates, such as:
How can that be achieved using mongoose, if at all?
You can use find
to establish the query and then chain a call to distinct
on the resulting query object to get the unique names in the result:
var search = 'Allan';
Name.find({name: new RegExp(search)}).distinct('name').exec(function(err, names) {...});
Or you can combine it all into a call to distinct
on the model, providing the query object as the second parameter:
var search = 'Allan';
Name.distinct('name', {name: new RegExp(search)}, function(err, names) {...});
In both cases, names
is an array of just the distinct names, not full document objects.
You can also do this with aggregate
which would then let you directly limit the number of results:
Name.aggregate([
{$match: {name: new RegExp(search)}},
{$group: {_id: '$name'}},
{$limit: 5}
])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With