mongodb aggregation, how to add a dynamic $limit C#?

Viewed 23

I have an exercise app to manipulate a lot of requests in mongoDB

The problem is that the data of the application is about 124680 documents, and I have to set a $limit at the beginning of the query so that it does not process all the data and the queries work faster.

Everything ok when I go to the first pages, but if I go to the last one, the request comes out empty, and I suppose that it must be the limit.

How can I add a dynamic limit?

 var response = _db.Terminales.Aggregate(new AggregateOptions { AllowDiskUse = true })
                .Match(filter)
                .Sort(sort)
                .Limit((200 * data.Limit) + data.Limit)
                .Project<terminal>(project)
                .Sort(sort1)
                .Group(key => key.serial, x => new
                {
                    _id = x.Key,
                    serial = x.Select(s => new Serial
                    {
                        AncestorNames = s.AncestorNames,
                        Family = s.Family,
                    }).First(),
                    StatusTerms = x.Select(s => s.statusTerm).Distinct(),
                })
                .Project<Result>(project2)
                .Match(filter2)
                .Sort(sort2)
                .Limit(data.Limit + data.Skip)
                .Skip(data.Skip)
                .ToList();

filter = Builders<terminal>.Filter.In(t => t.id, ids);
sort = new BsonDocument { { data.Projections[data.ColSort], data.Order } };
project = new BsonDocument { { "Family", 1 }, { "Installed", 1 }, { "historyAffiliate", new BsonDocument{ { "$slice", new BsonArray { "$historyAffiliate", -1 }} }}}; 
sort1 = new BsonDocument { { "historyAffiliate.initDate", -1 } }; 
sort2 = new BsonDocument { { paramproject, data.Order } };
0 Answers
Related