MongoDB的理解和总结GROUPBY

编程入门 行业动态 更新时间:2024-10-23 06:19:02
本文介绍了MongoDB的理解和总结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

本文发布于:2023-11-22 18:36:16,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1618543.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:MongoDB   GROUPBY

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!