MongoDB $first不支持的c#驱动程序错误

本文关键字:驱动程序 错误 不支持 first MongoDB | 更新日期: 2023-09-27 18:12:03

我在c#驱动程序中有一个这样的聚合查询:

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

匹配以下shell语法:

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

我认为c#版本不工作,因为CurrentStatus = group.First()["statuses"]和例外是:

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

我对First()约定的方法是基于以下的:

MongoDB c# Driver First Expression Reference

有什么办法把它翻译成司机喜欢的方式吗?

MongoDB $first不支持的c#驱动程序错误

在玩了一个类似的例子之后,看起来你可以先在你的组上调用Select来获得statuses字段,然后调用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();
相关文章: