Is there a built-in function to get all unique values in an array field, across all records?

56 Views Asked by At

My schema looks like this:

var ArticleSchema = new Schema({
...
  category: [{
    type: String,
    default: ['general']
  }],
...
});

I want to parse through all records and find all unique values for this field across all records. This will be sent to the front-end via being called by service for look-ahead search on tagging articles.

We can iterate through every single record and run go through each array value and do a check, but this would be O(n2).

Is there an existing function or another way that has better performance?

1

There are 1 best solutions below

0
On BEST ANSWER

You can use the distinct function to get the unique values across all category array fields of all documents:

Article.distinct('category', function(err, categories) {
    // categories is an array of the unique category values
});

Put an index on category for best performance.