From 9bbd1caa64b9073782275770da4e4b30299cb7eb Mon Sep 17 00:00:00 2001 From: ZhuchkaTriplesix Date: Tue, 16 Jun 2026 15:39:29 +0300 Subject: [PATCH] perf(mongodb): execute skip and limit pagination database-side Leverages to perform skip and limit query filters on the MongoDB server instead of retrieving the full stream and discarding documents client-side. --- lib/core/database/mongodb_service.dart | 33 ++++++++++++++------------ 1 file changed, 18 insertions(+), 15 deletions(-) diff --git a/lib/core/database/mongodb_service.dart b/lib/core/database/mongodb_service.dart index 620eb209..dc2566f5 100644 --- a/lib/core/database/mongodb_service.dart +++ b/lib/core/database/mongodb_service.dart @@ -126,23 +126,26 @@ class MongoService { return _withDb(connection, database, (db) async { final coll = db.collection(collection); - final selector = filter ?? {}; - - final stream = coll.find(selector); - final results = >[]; - int count = 0; - await for (final doc in stream) { - if (skip != null && count < skip) { - count++; - continue; - } - if (limit != null && results.length >= limit) { - break; + + final selector = where; + if (filter != null && filter.isNotEmpty) { + selector.raw(filter); + } + if (sort != null && sort.isNotEmpty) { + for (final entry in sort.entries) { + final isDesc = entry.value == -1 || entry.value == 'desc' || entry.value == 'DESC'; + selector.sortBy(entry.key, descending: isDesc); } - results.add(doc); - count++; } - return results; + if (skip != null && skip > 0) { + selector.skip(skip); + } + if (limit != null && limit > 0) { + selector.limit(limit); + } + + final stream = coll.find(selector); + return await stream.toList(); }); }