Home > Net >  Mongodb deleteMany or dump with specified date
Mongodb deleteMany or dump with specified date

Time:10-12

Maybe this subject often question to ask, but I not find what I want it. I have a collection with keys and values like this:

{
  _id: ObjectId("6142f3a47245125aef7ffcc0"),
  addTime: '2021-09-16 14:35:00',
  editTime: '2021-09-16 14:35:00'
}

I want to dump before August 2021. What syntax do I have to use? I trying in roboT and mongo shell, before dump I try find first.

db.collections.find({addTime:{$lte:new Date("2021-09-01")}})

and the result is

Fetched 0 record(s) in 3714ms

CodePudding user response:

You can make use of the $expr operator to temporarily convert the string to a date-time value and then perform your query.

db.collection.find({
  "$expr": {
    "$lte": [
      {
        "$dateFromString": {
          "dateString": "$addTime",
          "format": "%Y-%m-%d %H:%M:%S",  // <- Your date time format in string
          "onNull": new Date("9999-09-01"),  // <- Default calue if query key doesnt exist (Dont modify this value, unless required)
        }
      },
      new Date("2021-09-01"),  // <- Your datetime query value (can also be `ISODate` format)
    ],
  }
})

Mongo Playground Sample Execution

  • Related