简体   繁体   English

Mongodb 查询到select两个日期之间的所有文档

[英]Mongodb query to select all documents between two dates

I am currently struggling with this topic and I tried multiple solution from this platform like this one and found no results.我目前正在为这个话题苦苦挣扎,我尝试了这个平台的多种解决方案,但没有找到任何结果。

Basically I have an endpoint in a nestjs application that receives via a POST request a from and a to parameter that are both dates(string that can be converted with new Date(from/to) ).基本上我在 nestjs 应用程序中有一个端点,它通过 POST 请求接收一个from和一个to参数,这两个参数都是日期(可以用new Date(from/to)转换的字符串)。

I am trying to get all documents in the database between those two dates( from and to ).我试图在这两个日期( fromto )之间获取数据库中的所有文档。

Here is the query that I am making:这是我正在做的查询:

const data = await model.find( {
        payload: {
          timestamp: {
            $gte: new Date( from ).toISOString(),
            $lte: new Date( to ).toISOString()
          }
      }
} );

The response that I get is this error:我得到的响应是这个错误:

"Cast to date failed for value \"{ '$gte': 2023-01-03T14:15:52.767Z, '$lte': 2023-01-03T14:16:52.767Z }\" (type Object) at path \"timestamp\" for model \"data\"",

I also tried to get put the timestamp key outside the payload object so:我还尝试将时间戳密钥放在有效负载 object 之外,因此:

With error:有错误:

{payload:{timestamp: ... }}

query:询问:

const data = await model.find( {
        payload: {
          timestamp: {
            $gte: new Date( from ).toISOString(),
            $lte: new Date( to ).toISOString()
          }
      }
} );

Without error but I get an empty array every time:没有错误,但我每次都得到一个空数组:

{payload:{}, timestamp: ...}

query:询问:

const data = await model.find( {
   timestamp: {
       $gte: new Date( from ).toISOString(),
       $lte: new Date( to ).toISOString()
   }
} );

What exactly am I doing wrong?我到底做错了什么?

Using the discussion on this issue as the clue, the problem is in the query syntax here.这个问题的讨论为线索,问题出在这里的查询语法上。 Since you are using embedded fields, the query should use dot notation:由于您使用的是嵌入式字段,因此查询应使用点表示法:

const data = await model.find( {
  'payload.timestamp': {
     $gte: new Date( from ).toISOString(),
     $lte: new Date( to ).toISOString()
  }
} );

With the current syntax Mongoose is trying to construct a date object which is causing the Cast to date failed for value... (type Object) error.使用当前语法 Mongoose 试图构造一个日期 object,这导致Cast to date failed for value... (type Object)错误。 This syntax isn't what you'd want anyway as the database would be searching and comparing with the object which has different semantics than what you are likely looking for.无论如何,这种语法不是您想要的,因为数据库将搜索并与 object 进行比较,后者的语义与您可能正在寻找的语义不同。

Edit to add that more details about the query semantics on this topic can be found here in the documentation .编辑以添加有关此主题的查询语义的更多详细信息,请参见文档中的此处

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM