Search code examples
c#arraysmongodbprojection

Is it possible to project sub arrays and retrieve them as one array?


From the mongo sample let's say we have a collection like this;

{ "_id" : 1, "semester" : 1, "grades" : [ 70, 87, 90 ] }
{ "_id" : 2, "semester" : 1, "grades" : [ 90, 88, 92 ] }
{ "_id" : 3, "semester" : 1, "grades" : [ 85, 100, 90 ] }
{ "_id" : 4, "semester" : 2, "grades" : [ 79, 85, 80 ] }
{ "_id" : 5, "semester" : 2, "grades" : [ 88, 88, 92 ] }
{ "_id" : 6, "semester" : 2, "grades" : [ 95, 90, 96 ] }

and then the query is like this;

db.students.find( { semester: 1, grades: { $gte: 85 } },
                  { "grades.$": 1 } )

which results to this ;

{ "_id" : 1, "grades" : [ 87 ] }
{ "_id" : 2, "grades" : [ 90 ] }
{ "_id" : 3, "grades" : [ 85 ] }

I would like to have a result like ;

{"grades": [87, 90, 85]}

on one array.

c# code I implemented gives me array of LogLists, code is different then above but the operation is quite the same ;

 var result = collectionServerName.Find(x => x.LogList.Any(p => p.Ip.Contains("192")))
     .Project(Builders<ServerName>.Projection.Exclude("_id").Include("LogList"))
     .ToList();

I have tried following code;

var result = collectionServerName.Find(x => x.LogList.Any(p => p.Ip.Contains("192"))).Project(t => t.LogList.SelectMany(k => k)).ToList(); 

but it gives me following compile error for SelectMany

The type arguments for method 'Enumerable.SelectMany<TSource, TResult>(IEnumerable<TSource>, Func<TSource, IEnumerable<TResult>>)' cannot be inferred from the usage. Try specifying the type arguments explicitly

If I use only Select ;

var result = collectionServerName.Find(x => x.LogList.Any(p => p.Ip.Contains("192"))).Project(t => t.LogList.Select(k => k)).ToList();

The results type is List<IEnumarable<Log>> which I dont intend to have

The reason why I need as one array is I have to paginate the results before retrieving them. I am using c#. Any help would be appreciated.


Solution

  • What about this one for c# ?

    For all grades in one Enumerable

    collection .AsQueryable() .SelectMany(x => x.grades);

    And for paging just add Skip(10), Take(10) extension methods.