Question

I have lots of queries like sample1,sample2 and sample3. There are more than 13 million records in mongodb collection. So this query getting long time. Is there any way to faster this query?

I think using IMongoQuery object to resolve this problem. Is there any better way?

Sample 1:

var collection = new MongoDbRepo().DbCollection<Model>("tblmodel");
decimal total1 = collection.FindAll()
                .SelectMany(x => x.MMB.MVD)
                .Where(x => x.M01.ToLower() == "try")
                .Sum(x => x.M06);

Sample 2:

var collection = new MongoDbRepo().DbCollection<Model>("tblmodel");
decimal total2 = collection.FindAll().Sum(x => x.MMB.MVO.O01);

Sample 3:

var list1= collection.FindAll()
                     .SelectMany(x => x.MHB.VLH)
                     .Where(x => x.V15 > 1).ToList();

var list2= list1.GroupBy(x => new { x.H03, x.H09 })
                         .Select(lg =>
                               new
                               {
                                   Prop1= lg.Key.H03,
                                   Prop2= lg.Count(),
                                   Prop3= lg.Sum(w => w.H09),
                               });
Was it helpful?

Solution

The function FindAll returns a MongoCursor. When you add LINQ extension methods on to the FindAll, all of the processing happens on the client, not the Database server. Every document is returned to the client. Ideally, you'll need to pass in a query to limit the results by using Find.

Or, you could use the AsQueryable function to better utilize LINQ expressions and the extension methods:

var results = collection.AsQueryable().Where(....);

I don't understand your data model, so I can't offer any specific suggestions as to how to add a query that would filter more of the data on the server.

You can use the SetFields chainable method after FindAll to limit the fields that are returned if you really do need to return every document to the client for processing.

You also might find that writing some of the queries using the MongoDB aggregation framework might produce similar results, without sending any data to the client (except the results). Or, possibly a Map-Reduce depending on the nature of the data.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top