我的查询有问题。我的集合中有带有子字段 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/