gpt4 book ai didi

c# - C#中的MongoDB聚合函数

转载 作者:行者123 更新时间:2023-12-03 15:51:11 26 4
gpt4 key购买 nike

我试图在使用聚合函数后显示/列出数据,但它没有发生。

这段代码工作得很好。

        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);
}

此代码按原样获取文档,但是当我替换时
 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();

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

这是我的 Mongo 查询(我希望在 C# 中得到与此相同的结果)-
db.students.aggregate([{$sort:{_id:-1}},{$unwind:"$scores"},{$group:{_id:"$_id", lowscore:{"$min":"$scores.score"}}}])

最佳答案

构建聚合管道有点棘手。

尝试:

var pipeline = new BsonDocument[] {
new BsonDocument{ { "$sort", new BsonDocument("_id", 1) }},
new BsonDocument{{"$unwind", "$scores"}},
new BsonDocument{{"$group", new BsonDocument{
{"_id", "$_id"},
{"lowscore",new BsonDocument{
{"$min","$scores.score"}}
}}
}}
};

var result = collection.Aggregate<BsonDocument> (pipeline).ToListAsync();

如果你这样做 pipeline.ToJson() ,您将获得以下 JSON 等效字符串,该字符串与原始和经过测试的 MongoShell 查询相同。
[
{
"$sort": {
"_id": 1
}
},
{
"$unwind": "$scores"
},
{
"$group": {
"_id": "$_id",
"lowscore": {
"$min": "$scores.score"
}
}
}
]

关于c# - C#中的MongoDB聚合函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36399283/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com