node.js - mongoose 7.0.3 使用运算符 $and 严格搜索日期

标签 node.js mongodb mongoose mongodb-query

我的查询有问题。我的集合中有带有子字段 start_date 的对象。我需要在那一天进行严格的搜索。作为构建查询的一部分,我使用 $and 运算符,因此最终查询如下所示:

// I've tried this
 wb_collection_tracking_for_testing.countDocuments({ '$and': [ { 'CurrentState.start_date': '2021-07-01T00:00:00' } ] }, {})
// and this
wb_collection_tracking_for_testing.countDocuments({ '$and': [ { 'CurrentState.start_date': '2021-07-01' } ] }, {})
// and this
wb_collection_tracking_for_testing.countDocuments({ '$and': [ { 'CurrentState.start_date': new Date( '2021-07-01') } ] }, {})

对于 mongoose 7.0.3,它们都给出零。但至少最后一个在 mongosh 中给出了正确的结果。所以我的问题是如何使用运算符 $and 对子字段上的日期进行严格搜索?

UPD:集合中对象的示例(我仅包含与此查询字段相关的)start_date 在 mongoDB 中存储为 Date:

{ CurrentState: { start_date: 2022-01-01T00:00:00.000+00:00 }}

字段 start_date 未出现在架构中(它是使用 strict: false 选项创建的)。但我尝试将此字段添加到类型为 Date 的架构中,并且得到了相同的结果。

提前致谢!

最佳答案

MongoDB stores times in UTC ,所以你必须使用 Date.UTC() 转换你的日期例如或表示 UTC 时区的字符串:

const myDate = new Date(Date.UTC(2021, 06, 01)); // month index starts from 0
// Or
// const myDate = new Date('2021-07-01T00:00:00Z');

const result = await wb_collection_tracking_for_testing.countDocuments({ '$and': [ { 'CurrentState.start_date': myDate } ] }, {})

关于node.js - mongoose 7.0.3 使用运算符 $and 严格搜索日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75959968/

相关文章:

Java 考虑在添加 mongoDB 支持时在配置异常中定义一个类型的 bean

javascript - 根据用户的输入创建查询

javascript - 使用 findOne 更新 mongoDB 文档中的子字段并保存

c - 与 NodeJs 和 mbedtls 一起工作的加密程序

javascript - Node ,SSH2服务器等待输入

node.js - 添加大写 : true to mongoose embedded document

mongodb - 与MongoDB的友好关系

css - 如何在 Windows 上将 docker nginx 与 express 和 react 应用程序连接起来

mongodb - 将对象数组转换为 Mongoose 查询?

node.js - 从mongo中的多个集合中获取数据