MongoDB的理解和总结GROUPBY [英] Understanding MongoDB Aggregate and GroupBy
问题描述
我想通过ID做MongoDB中查询到第一组,然后降序排列。我有一个功能LINQ表达式在这里:
I'm trying to do a query in MongoDB to first group by id and then sort descending. I have a functional LINQ expression here:
var list = this.GetPackages().ToList();
list = list.OrderByDescending(package => package.PackageVersion)
.GroupBy(g => g.PackageId)
.Select(packages => packages.First()).ToList();
return list;
但我似乎无法拿出相当于MongoDB的表情,我也不能连得$项目功能工作:
But I can't seem to come up with the equivalent MongoDB expression, nor can I even get the $project function to work:
db.packages.aggregate([
{
$sort : { packageVersion : -1 }
},
{
$group: { _id: "$PackageId" }
},
{
$project: { PackageVersion: 1, Title: 1 }
}
])
我的结果是这样的:
{ "_id" : "e3afb1fe-dce7-476e-8372-cd8201abc131" }
{ "_id" : "e3722179-0903-4894-9a86-3a3ffd94de83" }
{ "_id" : "3e65e93a-4c2c-4a02-8b21-e5858a4058dd" }
格式正确的MongoDB的查询,是有一个相当于办法做到这一点使用C#MongoDB的驱动程序?
Is the MongoDB query of the correct format, and is there an equivalent way to do this using the C# MongoDB driver?
推荐答案
请使用 $第一个
运算符和的 $$ ROOT 变量获得该组中的第一个文档。
Make use of the $first
operator and $$ROOT variable to get the first document in the group.
$$ ROOT
是一个系统变量:
参考根文档,即顶级文档,目前$在聚合流水线级被处理b $湾
References the root document, i.e. the top-level document, currently being processed in the aggregation pipeline stage.
然后项目中第一个文件。
Then project the first document.
db.packages.aggregate([
{
$sort : { packageVersion : -1 }
},
{
$group: { "_id": "$PackageId","firstPackage":{$first:"$$ROOT"}}
},
{
$project: { "firstPackage": 1, "_id": 0}
}
])
这篇关于MongoDB的理解和总结GROUPBY的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!