C#中的MongoDB聚合函数 [英] MongoDB Aggregate function in C#

查看:108
本文介绍了C#中的MongoDB聚合函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用聚合功能后显示/列出数据,但是没有发生.

I am trying to display/list data after using aggregation function but it isn't happening.

此代码绝对可以正常工作.

This code works absolutely fine.

        var connectionstring = "mongodb://localhost:27017";
        var client = new MongoClient(connectionstring);
        var db = client.GetDatabase("school");
        var col = db.GetCollection<BsonDocument>("students");
        var filter = new BsonDocument("type", "homework");
        var filter2 = Builders<BsonDocument>.Filter.Eq("scores.type", "homework");

        var myresults = await col.Find(filter2)
            .Limit(2)
            .Project("{name:1,scores:1,_id:0}")
            .Sort("{score:1}")
            .ToListAsync();

        foreach (var result in myresults)
        {
            Console.WriteLine(result);
        }

此代码获取文档,但是当我替换

This code fetches document as it should however when I replace

 var myresults = await col.Find(filter2)
            .Limit(2)
            .Project("{name:1,scores:1,_id:0}")
            .Sort("{score:1}")
            .ToListAsync();

与此

            var myresults = await col.Aggregate()
            .Unwind("{$scores}")
            .Group(new BsonDocument { { "_id", "$_id" }, { "lowscore", new BsonDocument("$min", "$scores.score") } })
            //.Group("{_id:'$_id',lowscore:{$min:'$scores.score'}}")
            .ToListAsync();

没有记录被提取. 我不想使用管道方法.我只想显示通过聚合函数获得的结果.

No record is being pulled. I do not want to use Pipeline method. I simply want to display the result obtained via aggregate function.

这是我的Mongo查询(我想要与C#中的结果相同)-

This is my Mongo Query (I want the same result as this in C#)-

db.students.aggregate([{$sort:{_id:-1}},{$unwind:"$scores"},{$group:{_id:"$_id", lowscore:{"$min":"$scores.score"}}}])

推荐答案

这是错误的... {$scores}甚至不是有效的json.从$unwind指令中删除花括号和美元符号.

This is wrong... {$scores} isn't even valid json. Remove the curly braces and the dollar sign from the $unwind directive.

参数名称是字段,因此您需要为其提供字段名称.

The parameter name is field, so you need to provide a field name to it.

这篇关于C#中的MongoDB聚合函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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