数组中的聚合C#groupby
我有下面的结构,我想汇总一个电影列表,以获得所有演员和他们的形象数组中的聚合C#groupby,c#,mongodb,linq,aggregation-framework,mongodb-csharp-2.0,C#,Mongodb,Linq,Aggregation Framework,Mongodb Csharp 2.0,我有下面的结构,我想汇总一个电影列表,以获得所有演员和他们的形象 { "_id" : 1, "Title" : "Pirates of the Caribbean: The Curse of the Black Pearl", "Actors" : [ { "Name" : "Johnny Depp", "NameInMovie" : "Captain Jack Sparrow", "ImageUrl" : "Johnny-Depp.pn
{
"_id" : 1,
"Title" : "Pirates of the Caribbean: The Curse of the Black Pearl",
"Actors" : [
{
"Name" : "Johnny Depp",
"NameInMovie" : "Captain Jack Sparrow",
"ImageUrl" : "Johnny-Depp.png"
},
{
"Name" : "Geoffrey Rush",
"NameInMovie" : "Captain Hector Barbossa",
"ImageUrl" : "Geoffrey-Rush.png"
},
{
"Name" : "Orlando Bloom",
"NameInMovie" : "Will Turner",
"ImageUrl" : "Orlando-Bloom.png"
}
]
},
}
尝试使用Linq AsQueryable函数获取结果,但不支持:
var actors = Movies
.AsQueryable()
.SelectMany(x => x.Actors)
.GroupBy(x => x.Name)
.Select(a => a.First())
.ToList();
如何使用MongoDB driver2实现此功能
结果应该是这样的
{"Name" : "Johnny Depp",
"ImageUrl" : "Johnny-Depp.png" },
{"Name" : "Geoffrey Rush",
"ImageUrl" : "Geoffrey-Rush.png" },
{"Name" : "Orlando Bloom",
"ImageUrl" : "Orlando-Bloom.png" }
用
var actors = Movies.AsQueryable()
.SelectMany(x => x.Actors)
.GroupBy(x => new Actor { Name = x.Name, ImageUrl = x.ImageUrl })
.Select(x => x.Key)
.ToList();
这将给出以下查询
[{
"$unwind": "$Actors"
},
{
"$project": {
"Actors": "$Actors",
"_id": 0
}
},
{
"$group": {
"_id": {
"ImageUrl": "$Actors.ImageUrl",
"Name": "$Actors.Name"
}
}
},
{
"$project": {
"_id": "$_id"
}
}]
您很接近,但基本上没有在以下范围内实际选择属性: 因此,
.Select()
实际上需要与您使用的语法不同的语法。这将为您提供一个序列化的管道,如:
[
{
"$unwind" : "$Actors"
},
{
"$project" : {
"Actors" : "$Actors",
"_id" : 0
}
},
{
"$group" : {
"_id" : "$Actors.Name",
"__agg0" : {
"$first" : "$Actors.ImageUrl"
}
}
},
{
"$project" : {
"Name" : "$_id",
"ImgUrl" : "$__agg0",
"_id" : 0
}
}
],
IMHO并不是完全“最优的”,但这就是LINQ接口的优点
另外还有:
var results = Movies.AsQueryable()
.SelectMany( x => x.Actors )
.GroupBy( x => new { Name = x.Name, ImgUrl = x.ImageUrl })
.ToArray();
结果是:
[
{
"$unwind" : "$Actors"
},
{
"$project" : {
"Actors" : "$Actors",
"_id" : 0
}
},
{
"$group" : {
"_id" : {
"Name" : "$Actors.Name",
"ImgUrl" : "$Actors.ImageUrl"
}
}
}
],
它不使用,因此不是“完全”相同的东西,但在您的情况下,结果是相同的,因为ImgUrl
始终是Actor
上每个名称的相同值
var results = Movies.AsQueryable()
.SelectMany( x => x.Actors )
.GroupBy( x => new { Name = x.Name, ImgUrl = x.ImageUrl })
.ToArray();
[
{
"$unwind" : "$Actors"
},
{
"$project" : {
"Actors" : "$Actors",
"_id" : 0
}
},
{
"$group" : {
"_id" : {
"Name" : "$Actors.Name",
"ImgUrl" : "$Actors.ImageUrl"
}
}
}
],