Mongodb delete all dates less than specified

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 ,6etc.

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

Mongo also deletes 15,14,13, but stores dates in one day. Perhaps this is due to the fact that the date is a string?

I do not know how else to format the date, so I can delete all dates below a certain date.

This is supposed to be a cleaning process by deleting all documents with a date below that specified.

+4
source share
4 answers

Because the date field you are querying for is a string, not a Date (). In your mongo docs, instead of a custom date string, insert javascript date objects in the date field.

like

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

,

db.coll.remove({date:{$lte:new Date(2012, 7, 14)}})
+8

, . '15' '5'. ( , ).

:

db.coll.remove({
  date:{
    $lte : new Date(2012, 7, 14)
  }
})
+1

.

, "2014-3-5" , "2014-3-15", , , , "1" , "1", 5".

ISO, .

, , "" "" "" :

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 }
       );
   });
})

, .

0

MongoDB , , .

, , - , .

, ISODate Mongo, new Date, Mongo.

Mongo:

new Date(2017, 11, 1)

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

.

1 2017 .

:

new Date("2017-11-01")

:

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

, .

0

Source: https://habr.com/ru/post/1531900/


All Articles