distinct method detailed documentation
Overview
distinct is the field deduplication query method provided by monSQLize, which is used to obtain all unique values of the specified field from the MongoDB collection. Directly uses MongoDB's native Collection.distinct() method, which supports query condition filtering, sorting rules and extended options.
Method signature
Parameter description
field parameter
filter parameters
Query condition object, only matching documents are deduplicated, using MongoDB standard query syntax.
Type: Object
Required: No
Default value: {} (empty object means deduplication of all documents)
Example:
options parameter object
Core Options (MongoDB native ✅):
Extended options (monSQLize extension 🔧):
MongoDB reference documentation:
comment configuration
Query annotations are used to identify the purpose of deduplication queries in MongoDB logs and performance analysis tools.
Format Suggestions:
Usage Scenario:
- Filter Options: Identifies data sources for various drop-down lists and filters
- Data Statistics: Statistical query that identifies data dimensions
- Performance Analysis: Track the source of slow queries and help locate optimization points
Example:
session configuration
Execute a distinct query within a transaction:
Usage Scenario:
- Deduplication queries that need to ensure data consistency
- Executed in the same transaction as other write operations
- Queries that require isolation level guarantees
Note:
- session must be a valid MongoDB ClientSession object
- distinct queries in transactions will be affected by the transaction isolation level
- Transactions across sharded collections are not supported
collation configuration
Specify rules for string comparison and deduplication:
Guides:
- Requires case-insensitive deduplication (such as email, username)
- Correct deduplication in multi-language environments
- Natural deduplication of numeric strings
Return value
Normal mode returns array
By default, the distinct method returns a Promise, and resolve is an array of values after deduplication:
Return value type: Promise<Array<any>>
Notice:
- The type of array elements returned depends on the actual data type of the field
- If the field is an array type, the array will be expanded and deduplicated.
nulland non-existing fields will be treated as a unique value
explain mode returns execution plan
When explain is true or the specified level, returns the query execution plan:
Return value type: Promise<Object>
Usage mode
1. Basic deduplication query
The simplest way to remove duplicates, get all unique values of a specified field:
Applicable scenarios:
- Get enumeration values such as categories, tags, etc.
- Dimension value of statistics
- Build filter options
2. Conditional deduplication query
Combined with the query conditions, only matching documents are deduplicated:
Applicable scenarios:
- Statistics need to be based on specific conditions
- Dynamic filter options
- Data analysis and reporting
3. Nested field deduplication
Supports deduplication of nested fields:
Applicable scenarios:
- Field statistics for complex document structures
- Dimensional analysis of nested objects
4. Array field deduplication
When the field itself is an array, distinct will expand the array and remove duplicates:
Applicable scenarios:
- Tag cloud, keyword statistics
- All possible values for multi-select fields
- Classification aggregation
5. Case-insensitive deduplication
Use the collation configuration to achieve case-insensitive deduplication:
Applicable scenarios:
- Case-insensitive fields such as username and email address
- Multi-language text deduplication
- Standardized data statistics
6. Complex query conditions
Combined with MongoDB query operators to perform complex conditional deduplication:
Applicable scenarios:
- Data analysis and reporting
- Conditional filtering
- Business logic statistics
7. Enable caching
For frequently queried deduplication results, enabling caching can significantly improve performance:
Applicable scenarios:
- UI component data such as drop-down lists and filters
- Metadata and configuration items
- Statistics that change infrequently
Note:
- The cache time should not be too long to avoid data inconsistency
- It is not recommended to use cache in scenarios where data updates frequently
- Use
collection.invalidate('distinct')to clear cache manually
8. Performance Analysis
Use the explain parameter to view query performance and index usage:
Applicable scenarios:
- Performance optimization and debugging
- Index effect verification
- Slow query analysis
9. distinct query in transaction
Execute distinct queries in transaction context to ensure data consistency:
Applicable scenarios:
- Deduplication queries that need to ensure data consistency
- Executed in the same transaction as other write operations
- Queries that require isolation level guarantees
Note:
- session must be a valid MongoDB ClientSession object
- Queries within a transaction are affected by the isolation level
- Transactions across sharded collections are not supported
Performance optimization suggestions
1. Use index
Index fields that are frequently subjected to distinct queries:
Effect: -Significantly improve query speed
- Reduce the number of documents scanned
- Reduce server load
2. Reasonable use of query conditions
Narrow the query scope as much as possible and reduce the number of documents that need to be scanned:
3. Enable caching
For data that changes infrequently, enable caching:
4. Avoid deduplication of large array fields
The distinct operation on an array field containing a large number of elements can be slow:
FAQ
Q1: What is the difference between monSQLize's distinct and native MongoDB?
monSQLize's distinct() directly calls the native MongoDB's Collection.distinct() method, and provides extended functions on this basis:
Native MongoDB distinct:
monSQLize distinct (fully compatible + extended):
Extended function description:
- Cache support (
cache)
- Automatically cache query results to reduce database pressure
- Suitable for data that does not change frequently (categories, labels, etc.)
- Clear cache manually using
collection.invalidate('distinct')
- Performance Analysis (
explain)
- Return query execution plan instead of actual results
- Supports multiple verbosity levels:
'queryPlanner','executionStats','allPlansExecution' - Help optimize indexing and query performance
- Automatic event emission
- Emit
beforeDistinctandafterDistinctevents -Support query logging and monitoring
- Unified error handling
- Wrap native errors and provide more friendly error messages
- Integrated error handling mechanism of monSQLize
Core Principles:
- ✅ All native MongoDB distinct options are passed unchanged
- ✅ Extended options (cache, explain) are processed by monSQLize before calling native methods
- ✅ The behavior is fully compatible with native MongoDB, but provides additional convenient functions
Q2: What is the difference between distinct and aggregate + $group?
Q2: What is the difference between distinct and aggregate + $group? (FAQ)
distinct:
- Easy to use, intuitive syntax
- Specifically used for field deduplication
- Better performance optimization
- Does not support complex data conversion
aggregate + $group:
- More powerful functions, supporting complex aggregation
- Can calculate multiple fields at the same time
- Support data conversion and calculation
- The syntax is relatively complex
Selection Suggestions:
- Simple deduplication using
distinct - Requires calculations, transformations or multi-field aggregations using
aggregate
Q3: Is the array returned by distinct in order?
By default, the array returned by distinct is unordered. If sorting is required, it should be sorted manually after getting the results:
Q4: How to deal with null values?
distinct will return the null value as a unique value:
Q5: How to count the number of each unique value?
distinct returns only unique values, not counts. To count, use aggregate:
Q6: Does distinct support multi-field deduplication?
distinct only supports single field deduplication. If you need to combine multiple fields to remove duplicates, use aggregate:
Q7: How to use distinct in transactions?
Pass the ClientSession object with the session option:
Usage suggestions
When to use distinct
✅ Recommended usage scenarios:
- Get a list of enumeration values such as categories, tags, etc.
- Build drop-down lists and filter options
- Simple data dimension statistics
- No counting or other aggregation calculations required
❌ Not recommended scenarios:
- Need to count the number of each value (use
aggregate+$group) - Requires multi-field combination deduplication (use
aggregate) - Requires complex conversion of results (use
aggregate) - The field is a very large array with a large amount of data (consider the performance impact)
Performance considerations
Optimization points:
-
Create an index for distinct fields
-
Use query conditions to narrow the scope
-
Enable caching (data that changes infrequently)
-
Use explain to analyze performance
Caching strategy
Data suitable for caching:
- Metadata such as classification and tags (low frequency of change)
- List of enumeration values (status, role, etc.)
- Filter options (no real-time updates required)
Data not suitable for caching:
- Frequently updated fields -Statistics requiring real-time accuracy
- Sensitive data related to users
Cache duration recommendations:
Related methods
- find: Query multiple records and return complete documents
- findOne: Query a single record
- count: counts the number of documents
- aggregate: perform aggregation pipeline operations
Best Practices
1. Index optimization
Create indexes for commonly used distinct fields to significantly improve query performance:
2. Narrow the query scope
Use query criteria to reduce the number of documents that need to be scanned:
3. Proper use of cache
Enable caching for data that changes infrequently to reduce database pressure:
4. Performance analysis
Use explain to analyze query performance and optimize indexes:
5. Avoid deduplication of large array fields
The distinct operation on an array field containing a large number of elements can be slow:
6. Sorting results
The array returned by distinct is unordered and needs to be processed manually when sorting is required:
7. Add query comments
Use the comment option to identify the query purpose to facilitate log analysis:
8. Query in transaction
When data consistency is required, execute distinct in a transaction:
9. Handling null values
Decide whether to include null values based on business requirements:
10. Use collation to handle multiple languages
Use collation in multi-language environments to ensure correct deduplication:
Sample code
For more complete examples please refer to:
- distinct.ts - Current TypeScript usage examples
- queries.test.ts - Integration test coverage