Search code examples
c#mongodbmongodb-.net-driver

MongoDB Aggregate function in C#


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

Solution

  • 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.