Home > Software design >  Using Wildcard with ISODate MongoDB
Using Wildcard with ISODate MongoDB

Time:09-26

im trying to find all records that have a date that contains 00:00:00 in the hour minute and second portion to find documents that errored out in our subscription service. Was trying to use this but its erroring out.

db.CustomerSubscriptions.find({"UpcomingOrders.NextOrderDate": ISODate("/.*00:00:00.*/")})

CodePudding user response:

You can only apply regEx on String, hence you can use aggregation and find the matching records. pl refer here : https://mongoplayground.net/p/4o2h98R5jve

Sample code:

    db.collection.aggregate([
  {
    "$addFields": {
      "dateStrMatched": {
        $regexMatch: {
          input: {
            "$dateToString": {
              "date": "$date"
            }
          },
          regex: "00:00:00."
        }
      }
    }
  },
  {
    "$match": {
      dateStrMatched: true
    }
  }
])

Pipeline stage: Add field: convert date to string and match regex and store boolean flag as date matched or not match: to filter only matched dates

CodePudding user response:

You can use $dateToParts

db.CustomerSubscriptions.aggregate([
  { 
    $set: { 
      dateParts: {$dateToParts: {date: "$UpcomingOrders.NextOrderDate", timezone: ... } }
    } 
  },
  {$match: {"dateParts.hour": 0, "dateParts.minute": 0, "dateParts.second": 0} }
])
  • Related