C#中的MongoDB聚合函数

编程入门 行业动态 更新时间:2024-10-27 11:19:40
本文介绍了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聚合函数

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

发布评论

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

>www.elefans.com

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