C# MongoDB聚合查询计数
我正在向MongoDB和C#申请。我使用MongoDB C#驱动程序。我有以下收藏:C# MongoDB聚合查询计数,c#,mongodb,mongodb-.net-driver,C#,Mongodb,Mongodb .net Driver,我正在向MongoDB和C#申请。我使用MongoDB C#驱动程序。我有以下收藏: { _id: 5099803df3f4948bd2f98391, title: Toy Story, genres: [ "Animation", "Comedy" ] }, { _id: 5099803df3f4948bd2f98392, title: Minions, genres: [ "Animation", "Comedy", "Action" ] }
{
_id: 5099803df3f4948bd2f98391,
title: Toy Story,
genres: [ "Animation", "Comedy" ]
},
{
_id: 5099803df3f4948bd2f98392,
title: Minions,
genres: [ "Animation", "Comedy", "Action" ]
}
现在我想查询数据,得到每种类型的电影数量。因此,结果应该是:
Animation: 2
Comedy: 2
Action: 1
我正试图用这段代码实现这一点
database.GetCollection<Movie>("Movies")
.Aggregate()
.Unwind<Movie>(x => x.Genres)
.Group(x=>x.Genres, g => new
{
Genre= g.Key,
Count = g.Select(x=>x.Genres).Count()
}).ToList();
database.GetCollection(“电影”)
.Aggregate()
.diswind(x=>x.Genres)
.Group(x=>x.Genres,g=>new
{
类型=g.键,
Count=g.Select(x=>x.Genres).Count()
}).ToList();
我多次更改了它,但没有成功。这里使用Group()
来构建一个表达式,该表达式被转换到聚合的框架$Group
管道阶段。问题是MongoDB的语法与LINQ中的语法有点不同,因此您应该在这里更多地考虑“MongoDB方式”
从技术上讲,$group
将为您提供一个包含两个字段的文档集合:\u id
(这是分组键被翻译成的内容)和Count
。因此,要修复您的查询,您可以引入如下简单类型:
public class GenreStats
{
[BsonElement("_id")]
public string Genre { get; set; }
public int Count { get; set; }
}
然后使用该类型反序列化聚合结果:
database.GetCollection<Movie>("Movies")
.Aggregate()
.Unwind<Movie, Movie>(x => x.Genres)
.Group(x=>x.Genres, g => new
{
Count = g.Count()
}).As<GenreStats>().ToList();
database.GetCollection(“电影”)
.Aggregate()
.diswind(x=>x.Genres)
.Group(x=>x.Genres,g=>new
{
Count=g.Count()
}).As().ToList();