如何使用mongodb和c#在子元素中使用聚合函数? [英] how use aggregate functions in child elements using mongodb and c#?

查看:222
本文介绍了如何使用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#在子元素中使用聚合函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆