【问题标题】:C# MongoDB query: filter based on the last item of arrayC# MongoDB 查询:根据数组的最后一项进行过滤
【发布时间】:2022-11-19 05:28:55
【问题描述】:

我有一个像这样的 MongoDB 集合:

{
    _id: "abc",
    history: 
    [
        {
            status: 1,
            reason: "confirmed"
        },
        {
            status: 2,
            reason: "accepted"
        }
    ],
    _id: "xyz",
    history: 
    [
        {
            status: 2,
            reason: "accepted"
        },
        {
            status: 10,
            reason: "cancelled"
        }
    ]
}

我想在 C# 中编写查询以返回其文档最后的历史项目为 2(已接受)。所以在我的结果中我不应该看到“xyz”,因为它的状态已经从 2 改变了,但是我应该看到“abc”,因为它的最后状态是 2。问题是获取最后一项使用 MongoDB 的 C# 驱动程序并不容易——或者我不知道如何操作。

我尝试了 linq 的 lastOrDefault 但得到了 System.InvalidOperationException: {document}{History}.LastOrDefault().Status is not supported 错误。

我知道有一个解决方法可以先获取文档(加载到内存)然后进行过滤,但它是客户端并且速度很慢(消耗大量网络)。我想在服务器上做过滤器。

【问题讨论】:

    标签: c# arrays mongodb mongodb-query mongodb-.net-driver


    【解决方案1】:

    选项 1) 查找()

    db.collection.find({
     $expr: {
      $eq: [
      {
        $arrayElemAt: [
          "$history.status",
          -1
        ]
        },
        2
      ]
     }
    })
    

    Playground1

    选项 2) 聚合

    db.collection.aggregate([
     {
    "$addFields": {
      last: {
        $arrayElemAt: [
          "$history",
          -1
        ]
       }
      }
    },
    {
      $match: {
        "last.status": 2
      }
    },
    {
     $project: {
      "history": 1
      }
     }
    ])
    

    Playground2

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-03-11
      • 2021-12-28
      • 1970-01-01
      • 1970-01-01
      • 2020-07-30
      • 2015-11-15
      • 2018-05-04
      相关资源
      最近更新 更多