Mongoose: return unique result set without duplicate records

I am using Mongoose in a MEAN environment. How can I make sure I don't have duplicate results in my result set? Example: my database contains 10 (partially 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 perhaps just "all" (using .find (regex ...) and limiting the number of results returned to 5, I get this:

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

With three duplicate "Allan" entries, we are wasting a lot of variety in the results (talking about the autocomplete feature for the search input field). I want a returnable result set without duplicates, like this:

  • Allan
  • Allan Fourier
  • Allan Maxwell
  • Allan foo
  • Allan Whatever

How can this be achieved with a mongoose, if at all?

+3


source to share


3 answers


You can use find

to set the request and then chain the call distinct

on the resulting request object to get 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 distinct

model call by providing the request object as the second parameter:

var search = 'Allan';
Name.distinct('name', {name: new RegExp(search)}, function(err, names) {...});

      



In both cases, it names

is an array of individual names only, not complete document objects.

You can also do this with aggregate

, which will then allow you to directly limit the number of results:

Name.aggregate([
    {$match: {name: new RegExp(search)}},
    {$group: {_id: '$name'}},
    {$limit: 5}
])

      

+6


source


You can use a MongoDB query distinct()

to only find individual values ​​(i.e., unique values) in your set. In the API docs , various can be used with Mongoose.

Example:



{ "_id": 1, "dept": "A", "item": { "sku": "111", "color": "red" }, "sizes": [ "S", "M" ] }
{ "_id": 2, "dept": "A", "item": { "sku": "111", "color": "blue" }, "sizes": [ "M", "L" ] }
{ "_id": 3, "dept": "B", "item": { "sku": "222", "color": "blue" }, "sizes": "S" }
{ "_id": 4, "dept": "A", "item": { "sku": "333", "color": "black" }, "sizes": [ "S" ] }

      

C db.inventory.distinct( "dept" )

will return[ "A", "B" ]

0


source


You can filter the search result that is an array using the method suggested here:

Remove duplicate from array

0


source







All Articles