如何使用mongodb和c#在子元素中使用聚合函数?

编程入门 行业动态 更新时间:2024-10-26 19:25:56
本文介绍了如何使用mongodb和c#在子元素中使用聚合函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个庞大的c#类:

I have a c# class that is a massive collection:

public class Usuario_Series_Episodios { public void Dispose() { GC.SuppressFinalize(this); } [BsonId] public ObjectId _id { get; set; } public int Usuario_Id { get; set; } public int Serie_Id { get; set; } public IList<EpisodiosVistos> EpisodiosVistos { get; set; } } public class Episodes : Entity { public virtual int User_Id { get; set; } public virtual string User_Name { get; set; } public virtual int Serie_Id { get; set; } public virtual string Cod_Serie { get; set; } public virtual int Episode { get; set; } public virtual string Cod_Eps { get; set; } public virtual DateTime Date { get; set; } }

我需要查询按系列分组的上周最受关注的剧集,我的搜索结果需要按降序排列,如下所示:

I need to query the most watched episodes of last week grouped by series,my result needs order by descending is like this:

Serie_id-情节-计数

Serie_id -- Episode -- Count

1 -------------- 2 ---------- 20

1--------------2----------20

3 -------------- 4 ---------- 19

3--------------4----------19

1 -------------- 3 ---------- 18

1--------------3----------18

所以我做了下面的代码:

so I did the code below :

var collection =db.GetCollection<BsonDocument>("Usuario_Series_Episodios"); var aggregate = collection.Aggregate() .Group( new BsonDocument { { "_id", "$EpisodiosVistos.Serie_Id" }, { "episodio", "$EpisodiosVistos.Episode" }, { "count", new BsonDocument("$sum", 1) } }); var results = await aggregate.SortByDescending(bson => bson["count"]).ToListAsync();

但出现以下错误:

命令聚合失败:组聚合字段'episodio'必须为 定义为对象内部的表达式.

Command aggregate failed: the group aggregate field 'episodio' must be defined as an expression inside an object.

有人可以帮助我吗?

推荐答案

我对MongoDB的.NET驱动程序不是很熟悉,但是下面是这样的想法:

I'm not super familiar with the .NET Driver for MongoDB, but below is the idea:

var aggregate = collection.Aggregate() .Group( new BsonDocument { { "_id", new BsonDocument{{ "series", "$Serie_Id"}, { "episodio", "$EpisodiosVistos.Episode" }} }, { "count", new BsonDocument("$sum", 1) } });

如果要按多个字段分组,则都需要将它们都包含在_id字段中进行分组.之后的所有字段都是累加器,它们必须是某种形式的表达式,这就是为什么编译器抱怨episodio不是表达式.

If you want to group by multiple fields, they both need to be included in the _id field for the grouping. All of the fields after that are accumulators which need to be expressions of some kind, which is why the compiler was complaining about episodio not being an expression.

更多推荐

如何使用mongodb和c#在子元素中使用聚合函数?

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

发布评论

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

>www.elefans.com

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