Reputation: 2240
I have the following entity collection:
public class Branch
{
[BsonId]
public ObjectId Id { get; set; }
public string Description { get; set; }
public ObjectId PartnerId { get; set; }
public IEnumerable<Discount> Discounts { get; set; }
}
I want to group by PartnerId and select PartnerId, first not null Description and concatenate (SelectMany) all of the Discounts arrays in the group. Basically the desired result is an array of:
public class GroupProjection
{
public ObjectId PartnerId { get; set; }
public string Description { get; set; }
public IEnumerable<Discount> Discounts { get; set; }
}
Is it done with AggregateAsync API?
I've just started with mongodb and mongo c# driver. Is is possible using Linq or do I have to resort to JScript group definitions to build a pipeline?
I've took a look through tests for c# driver but it is not quite obvious, since they use internal helpers to build Bson documents with grouping criteria.
Upvotes: 3
Views: 4052
Reputation: 21245
The MongoDB fluent API currently does not support the SelectMany
extension method. However, you can workaround this.
var groupResult =
await collection
.Aggregate()
.Group(
x => x.PartnerId,
g => new
{
PartnerId = g.Key,
Description = g.First(x => x.Description != null).Description,
Discounts = g.Select(x => x.Discounts)
})
.ToListAsync();
var result =
groupResult
.Select(x =>
new GroupProjection
{
PartnerId = x.PartnerId,
Description = x.Description,
Discounts = x.Discounts.SelectMany(d => d)
})
.ToList();
Upvotes: 2