我试图找到一种查询mongodb集合的方法:在'history'数组中,'running'的state值为also the latest entry的所有文档都应该被返回.

我可以在C#中使用.max()和.OrderBy()使用LINQ,but not in nodeJS.

C#不含polymer :

var filter = Filter.Where(w => w.history.OrderBy(o => o.createdAt).Last().status == "running")

以下是示例文档:

{
  _id: 1,
  name: 'name 1',
  history: [
    {
     createdAt: '2024-01-01',
     state: 'initialized'
    },
    {
     createdAt: '2024-01-15',
     state: 'running'
    },
    {
     createdAt: '2024-02-02',
     state: 'stopped'
    }
  ]
},
{
  _id: 2,
  name: 'name 2',
  history: [
    {
     createdAt: '2024-01-01',
     state: 'initialized'
    },
    {
     createdAt: '2024-01-20 01:15:66',
     state: 'running'
    },
    {
     createdAt: '2024-01-21 00:55:59', // this is the LATEST entry, and state=running --> return document
     state: 'running'
    },
    {
     createdAt: '2024-01-21 00:55:58',
     state: 'stopped'
    }
  ]
}

A state can be there more than once, so the history array could contain 'running' 3 times. In that case I would need to return the latest entry (using createdAt). It being the last entry in the array does not mean its createdAt date is the latest date.

推荐答案

从mongoDB版本5.2开始,一个选项是使用$sortArray:

db.collection.aggregate([
  {$match: {
      $expr: {$eq: [
          {$getField: {
              input: {$first: {$sortArray: {input: "$history", sortBy: {createdAt: -1}}}},
              field: "state"
          }},
          "running"
      ]}
  }}
])

看看它在mongoDB playground号公路上是如何工作的

Node.js相关问答推荐

Windows上使用ES6+的OpenAPI规范的Express服务器不接受嵌套路由'

Mongoose:如何在文档中推送到Caped(有限大小,滚动窗口)数组?

(0,core_1.default)不是使用@middy/core的lambda处理程序上的函数

如何在MongoDB中更新嵌套数组

如何将Node.js与Nuxt.js一起使用?

使用NodeJS的DynamoDB中的BatchGetItem出现MultipleValidationError

在Docker容器404页面中找不到服务器(提供静态reactjs文件)

Sequelize、postgres和posgis:在n°;公里

如何使用Next.js/Node/TS正确地上传至S3

处理嵌套元素时,使用xml2js库解析XML时发生错误

我如何在 Raku 的供应中注册不同的事件?

使用react 组件加载特定 DIV 而无需重新加载整个页面

访问 Mongoose 查询之外的变量

nuxt:在 docker 镜像中找不到

NestJS 共享模块的问题

根据 mongoDB 中存在的唯一字符串生成唯一字符串的最佳方法

如何在 cypress 测试中进行计算

带权限的机密 Rest-Api - 总是 403 - 我做错了什么?

Node.js 应用程序有周期性的缓慢和/或超时(不接受传入的请求)

为什么 Node.js 被命名为 Node.js?