As a follow up to this question , where I needed to aggregate over inner arrays in MongoDB, I am trying to accomplish the same task in LINQ.
I am close, as I have figured out how to aggregate over an individual item:
// Get collection
var collection = _database.GetCollection<VehicleDataUpload>("Vehicles");
// Get first project that meets our identifier
var firstProject = collection.AsQueryable().Where(i => i.ProjectId.Equals("1234")).First();
// Get a list of DailySummaryData objects
var aggregation =
from entry in firstProject.VehicleEntries
group entry by entry.Data
into result
select new DailySummaryData() {
ProjectName = firstProject.ProjectId,
Date = result.FirstOrDefault().Date,
Passed = result.Sum(x => (x.VehicleStatus.Equals("PASSED") ? 1 : 0)),
Failed = result.Sum(x => (x.VehicleStatus.Equals("FAILED") ? 1 : 0))
};
return aggregation.ToList();
However, I can't use ...First()
on the collection, because there might be multiple VehicleDataUploads for a project. How can I aggregate over all the lists inside the list of documents that are returned?
Try something as follows:
// Get collection
var collection = _database.GetCollection<VehicleDataUpload>("Vehicles");
// Get first project that meets our identifier
var aggregation = collection
.AsQueryable()
// This will return an IEnumerable of Vehicles object
.Where(i => i.ProjectId.Equals("1234"))
// Assuming you want to return a plain list, you should use SelectMany
.SelectMany(v => v.VehicleEntries
// You group each list of VehicleEntries
.GroupBy(ve => ve.Data)
// For each group you return a new DailySummaryData object
.Select(g => new DailySummaryData() {
ProjectName = v.ProjectId,
Date = g.Key,
Passed = g.Sum(x => (x.VehicleStatus.Equals("PASSED") ? 1 : 0)),
Failed = g.Sum(x => (x.VehicleStatus.Equals("FAILED") ? 1 : 0))
})
return aggregation.ToList();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.