Finding Distinct Field Values

A very useful query against a MongoDB collection is to get a list of the distinct values for a single field in a set of documents. Distinct in this case means that even though there are thousands of documents, you only want to know the unique values that exist.

The distinct() method on Collection objects allows you to find a list of distinct values for a specific field. The syntax for the distinct() method is shown below:

distinct(key,[query],[options],callback)

The key parameter is the string value of the fieldname you want to get values for. You can specify subdocuments by using the dot syntax—for example, stats.count. The query parameter is an object with the standard query object ...

Get Node.js, MongoDB, and AngularJS Web Development now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.