Search code examples
node.jsmongodbmongoosemongodb-query

mongoose 7.0.3 strict search on date with operator $and


I have the problem with my query. I have objects in my collection with subfield start_date. And I need strict search on that date. As part of constructing my query I use $and operator so the final query looks like:

// 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') } ] }, {})

and they all give zero with mongoose 7.0.3. But at least the last one gives the right result in mongosh. So my question is How to use strict search with dates on subfields with usage of operator $and?

UPD: The example of the object in the collection (I've included only related to this query fields) start_date is stored as Date in mongoDB:

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

Field start_date is not presented in the schema (it is created with a strict: false option). But I've tried to add this field to the schema with type Date and I've got the same result.

Thanks in advance!


Solution

  • MongoDB stores times in UTC, so you have to convert your date using Date.UTC() for example or a string representing the UTC time zone:

    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 } ] }, {})