Home > Blockchain >  Mongo database query operation question on dates as string
Mongo database query operation question on dates as string

Time:11-24

Let’s say some external component inserts data into my mongo database with Field called “startDate”. They store the value as string in mongo db in format yyyymmdd-HHmmss.

Can I still run the date time queries to fetch documents between two dates ?

Will below work as expected for above scenario?

db.test.find({ startDate:{$gt: “20201121”, $lte: “20210121”}})

CodePudding user response:

Yes, it will but not for the same end date. It'd be better to add a day to cater for trailing zeros.

//data
[
  {
    startDate: "20210101-010101"
  },
  {
    startDate: "20210121-000000"
  },
  {
    startDate: "20210121-010000"
  }
]

// query 1 - not successful maybe

[
  {
    startDate: "20210101-010101"
  },
  {
    startDate: "20210121-000000"
  },
  {
    startDate: "20210121-010000"
  }
]

//query 2, successful
db.collection.find({
  startDate: {
    $gt: "20201121",
    $lt: "20210122"
  }
})
  • Related