MongoDB Aggregate function in C#

2020-08-01 06:12发布

问题:

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

with this

            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.

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"}}}])

回答1:

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.



回答2:

Building aggregation pipeline is bit tricky.

Try:

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

If you do pipeline.ToJson(), you'll get following JSON equivalent string which is same as of your original and tested MongoShell query.

[
    {
        "$sort": {
            "_id": 1
        }
    },
    {
        "$unwind": "$scores"
    },
    {
        "$group": {
            "_id": "$_id",
            "lowscore": {
                "$min": "$scores.score"
            }
        }
    }
]


回答3:

Try with writing only $score instead of @scores.score. may be it helpful.

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