Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mongodb remove all dates less than specified

Tags:

date

mongodb

I have the following data.

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

And some lower dates, like 2014-3-9 , 8 ,7 ,6 etc.

When doing a db.coll.remove({date:{$lte:"2014-3-5"}})

Mongo removes the 15,14,13 aswell, but keeps single digit day dates. Is this maybe due to the date is a string?

I dont know how else to format the date so I can remove all dates below a certain date.

It is supposed to be a cleaning process, removing all documents with a date lower than specified.

like image 819
user3422790 Avatar asked Mar 15 '14 09:03

user3422790


3 Answers

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)}})
like image 159
Mithun Satheesh Avatar answered Nov 08 '22 15:11

Mithun Satheesh


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.

like image 37
Abdul Rahman A Samad Avatar answered Nov 08 '22 17:11

Abdul Rahman A Samad


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)
  }
})
like image 1
Salvador Dali Avatar answered Nov 08 '22 15:11

Salvador Dali