Home > Software engineering >  How to convert string to date and then perform a filter with mongodb?
How to convert string to date and then perform a filter with mongodb?

Time:10-31

enter image description here

How do I convert the field date of type String to Date before doing a filter to get all dates greater than the current date? Thanks!

CodePudding user response:

data

[
  {
    _id: 1,
    item: "apple",
    qty: 5,
    order_date: new Date("2018-03-10")
  },
  {
    _id: 2,
    item: "pie",
    qty: 10,
    order_date: new Date("2018-03-12")
  },
  {
    _id: 3,
    item: "ice cream",
    qty: 2,
    price: "4.99",
    order_date: "2018-03-05"
  },
  {
    _id: 4,
    item: "almonds",
    qty: 5,
    price: 5,
    order_date: "2018-03-05  10:00"
  }
]

$toDate

db.collection.aggregate([
  {
    $addFields: {
      convertedDate: {
        $toDate: "$order_date"
      }
    }
  }
])

mongoplayground

CodePudding user response:

  1. $toDate - Convert date string to Date.
  2. $$NOW - Variable to get current datetime.
  3. $expr - Allow aggregration expression within the query language.
db.collection.find({
  $expr: {
    $gt: [
      {
        $toDate: "$date"
      },
      "$$NOW"
    ]
  }
})

Sample Mongo Playground

  • Related