Error unsupported error MongoDB $ C #

I have an aggregation request in a C # driver as follows:

var result = await _records.Aggregate() .Match(record => record.Statuses.Any(status => status.Status == currentStatus)) .Unwind(record => record.Statuses) .Sort(Builders<BsonDocument>.Sort.Descending("statuses.date")) .Group(doc => doc["_id"], group => new { Id = group.Key, CurrentStatus = group.First()["statuses"] }) .Match(arg => arg.CurrentStatus["status"] == BsonValue.Create(currentStatus.ToString())) .ToListAsync(); 

which corresponds to the following shell syntax:

 db.records.aggregate( [ { $match : { "statuses.status" : "Finished" } }, { $unwind: "$statuses" }, { $sort: { "statuses.date":-1 } }, { $group: { _id: "$_id", current_status: { $first: "$statuses" } } }, { $match : { "current_status.status" : "Finished" } } ]) 

I think the C # version is not working due to CurrentStatus = group.First()["statuses"] , and the exception is:

 System.NotSupportedException: get_Item of type MongoDB.Bson.BsonValue is an unsupported method in a $project or $group pipeline operator. 

My approach for the First() convention is based on this:

MongoDB C # Driver First Expression Reference

Any ideas on how to translate it the way he likes?

+5
source share
1 answer

After playing with a similar example for bits, it looks like you can do this by first typing Select in your group to get the statuses field, and then calling First() :

 var result = await _records.Aggregate() .Match(record => record.Statuses.Any(status => status.Status == currentStatus)) .Unwind(record => record.Statuses) .Sort(Builders<BsonDocument>.Sort.Descending("statuses.date")) .Group(doc => doc["_id"], group => new { Id = group.Key, CurrentStatus = group.Select(x => x["statuses"]).First() }) .Match(arg => arg.CurrentStatus["status"] == BsonValue.Create(currentStatus.ToString())) .ToListAsync(); 
+1
source

All Articles