In Mongoose, if you want to query unique values, you can use the distinct method. This method returns all unique values for a specified field within a document collection.
Here's an example of using the distinct method: Suppose you have a model named User with an email field, and you want to query all unique email addresses.
javascriptconst uniqueEmails = await User.distinct('email'); console.log(uniqueEmails);
This code returns an array containing all unique email addresses.
If you want to further filter the query results, such as retrieving only unique email addresses for users with verified accounts, you can add query conditions to the distinct method:
javascriptconst uniqueVerifiedEmails = await User.distinct('email', { isVerified: true }); console.log(uniqueVerifiedEmails);
In this example, the second parameter { isVerified: true } specifies a query condition that returns distinct values for the email field, but only for documents where isVerified is true.
Using the distinct method is a good choice for efficiently querying distinct values when dealing with large document collections. However, note that performance is affected by the database index configuration. Therefore, to improve query efficiency, appropriate indexes should be created on the relevant fields.