Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose: Returning unique result set with no duplicate entries

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:

  • Allan
  • Allan Fourier
  • Allan
  • Allan Maxwell
  • Allan
  • Allan Foo
  • Allan Whatever
  • Allan Whoever
  • Allan Smith
  • Allan Rogers

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:

  • Allan
  • Allan Fourier
  • Allan
  • Allan Maxwell
  • Allan

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:

  • Allan
  • Allan Fourier
  • Allan Maxwell
  • Allan Foo
  • Allan Whatever

How can that be achieved using mongoose, if at all?

like image 475
Igor P. Avatar asked May 04 '15 00:05

Igor P.


1 Answers

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}
])
like image 149
JohnnyHK Avatar answered Oct 26 '22 13:10

JohnnyHK