mongodb remove all dates less than specified

前端 未结 4 1112
孤独总比滥情好
孤独总比滥情好 2021-01-02 06:50

I have the following data.

{
    deviceID: 186,
    date: \"2014-3-15\"
}
{
    deviceID: 186,
    date: \"2014-3-14\"
}
{
    deviceID: 186,
    date: \"201         


        
相关标签:
4条回答
  • 2021-01-02 07:18

    The reason for this is is your dates are strings.

    So in a lexical sense when comparing strings "2014-3-5" is greater than "2014-3-15", as what is being compared is that "1" is less than "5".

    Fix your dates as real ISO Dates, or you will forever have this problem.

    Batch convert like this, assuming "year" "month" "day" in format:

    db.eval(function(){
    
       db.collection.find().forEach(function(doc) {
           var d = doc.date.split("-");
           var date = new Date( 
               "" + d[0] + "-" +
              ( d[1] <= 9 ) ? "0" + d[1] : d[1] + "-" +
              ( d[2] <= 9 ) ? "0" + d[2] : d[2]
           );
           db.collection.update(
               { "_id": doc._id },
               { "$set": { "date": date }
           );
       });
    })
    

    That makes sure you get the right dates on conversion.

    0 讨论(0)
  • 2021-01-02 07:28

    If you want to remove data from MongoDB from the date less than specified, you MUST make sure of the date.

    Easiest way for you to check whether you are inputting the right format is to test it before you use it in your query.

    For example if you want to get current date in ISODate in Mongo shell, just type new Date and you will get the current date in Mongo.

    I've tried the following in the Mongo shell:

    new Date(2017, 11, 1)
    

    and it returns

    ISODate("2017-11-30T16:00:00Z")
    

    which is not what I wanted.

    What I want is to delete data before 1 November 2017.

    Here's what works for me:

    new Date("2017-11-01")
    

    and it returns:

    ISODate("2017-11-01T00:00:00Z")
    

    Which is what I wanted.

    0 讨论(0)
  • 2021-01-02 07:33

    Its because the date field you are querying on is a string filed and not a Date(). In your mongo documents instead of a custom date string, insert javascript date objects into date field.

    like

    { deviceID: 186,,"date": new Date(2012, 7, 14) }
    

    and when you execute the remove do it like

    db.coll.remove({date:{$lte:new Date(2012, 7, 14)}})
    
    0 讨论(0)
  • 2021-01-02 07:36

    This is because you are storing your data in a wrong format. You have a string an string '15' is smaller than string '5'. Convert your strings in the beginning to date (read here how to use dates in mongo).

    And only than you can use it to properly compare your dates:

    db.coll.remove({
      date:{
        $lte : new Date(2012, 7, 14)
      }
    })
    
    0 讨论(0)
提交回复
热议问题