Skip to content

Commit a87624b

Browse files
committed
perf(mongodb): optimize selector construction in MongoDB queries
- Simplify the selector building process for non-filtered queries - Refactor the filter handling to improve query performance and readability - Add logging for built selectors to aid in debugging and query analysis
1 parent 925354e commit a87624b

File tree

1 file changed

+17
-5
lines changed

1 file changed

+17
-5
lines changed

lib/src/ht_data_mongodb.dart

Lines changed: 17 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -138,14 +138,26 @@ class HtDataMongodb<T> implements HtDataClient<T> {
138138
/// Note: The `userId` parameter is intentionally ignored here, as this
139139
/// schema does not use a `userId` field for scoping.
140140
Map<String, dynamic> _buildSelector(Map<String, dynamic>? filter) {
141-
final selector = <String, dynamic>{};
141+
if (filter == null || filter.isEmpty) {
142+
_logger.finer('Built MongoDB selector: {}');
143+
return {};
144+
}
142145

143-
if (filter != null) {
144-
// The filter map is assumed to be in valid MongoDB query format,
145-
// so we can merge it directly.
146-
selector.addAll(filter);
146+
// If there's only one filter condition, we don't need to wrap it in $and.
147+
if (filter.length == 1) {
148+
_logger.finer('Built MongoDB selector: $filter');
149+
return filter;
147150
}
148151

152+
// If there are multiple conditions, wrap them in an explicit $and operator
153+
// to ensure they are all applied correctly. This makes the query more
154+
// robust and avoids potential ambiguity.
155+
final andConditions = filter.entries
156+
.map((entry) => {entry.key: entry.value})
157+
.toList();
158+
159+
final selector = {r'$and': andConditions};
160+
149161
_logger.finer('Built MongoDB selector: $selector');
150162
return selector;
151163
}

0 commit comments

Comments
 (0)