Delete old records in mongodb

I have the following type of records in Mongo DB.

{
    "_id" : ObjectId("50217d8874ebb0e4e52cc07d"),   
    "timestamp" : "8/7/12 1:41:36 PM Pacific Daylight Time",
    "_ts" : ISODate("2012-08-07T20:41:44.119Z")
}

How to delete old records? I tried something like db.offlineLogs.remove({timestamp: {$lt:new Date("2012, 8, 3")}});, but it does not work.

+5
source share
3 answers

In the original request timestamp, this is just a string field, and Date()will be considered as a string in the Mongo shell. Comparing these operands will work like any other string comparison:

$ mongo
MongoDB shell version: 2.2.0-rc1-pre-
connecting to: test
> db.foo.drop()
true
> db.foo.insert({ x: Date() });
> db.foo.find()
{ "_id" : ObjectId("50218e808930273947a21cf3"), "x" : "Tue Aug 07 2012 17:54:09 GMT-0400 (EDT)" }
> sleep(1000)
null
> db.foo.find({ x: { $lt: Date() }});
{ "_id" : ObjectId("50218e808930273947a21cf3"), "x" : "Tue Aug 07 2012 17:54:09 GMT-0400 (EDT)" }
> db.foo.find({ x: { $gt: Date() }});
> 

ISODate()is the JS equivalent for Mongo date fields , and it is not comparable to string values ​​when using $gtor $lt:

> db.foo.find({ x: { $gt: ISODate() }});
> db.foo.find({ x: { $lt: ISODate() }});
> db.foo.find({ x: { $ne: ISODate() }});
{ "_id" : ObjectId("50218e808930273947a21cf3"), "x" : "Tue Aug 07 2012 17:54:09 GMT-0400 (EDT)" }
> db.foo.insert({x: ISODate() });
> db.foo.find({ x: {$gt: Date() }});
> db.foo.find({ x: {$lt: Date() }});
{ "_id" : ObjectId("50218e808930273947a21cf3"), "x" : "Tue Aug 07 2012 17:54:09 GMT-0400 (EDT)" }
> db.foo.find({ x: {$ne: Date() }});
{ "_id" : ObjectId("50218e808930273947a21cf3"), "x" : "Tue Aug 07 2012 17:54:09 GMT-0400 (EDT)" }
{ "_id" : ObjectId("50218fa18930273947a21cf4"), "x" : ISODate("2012-08-07T21:58:57.350Z") }
>

Mongo , , , .

: , -, (, ), TTL, 2.2. .

+1

: db.offlineLogs.remove({"_ts":{"$lt":ISODate("2012-08-01T19:30:07.805Z")}});

+6

TimeToLive.

MongoDB TimeToLive, , , .

, , billing :

{ 
    "_id" : ObjectId("59a05ef17055161ef66e9b21"), 
    "receiptId" : NumberInt(31124124), 
    "salesperson" : "jack", 
    "salesTime" : ISODate("2017-08-25T17:32:23.157+0000")
}

, :

db.billing.createIndex( { "salesTime": 1 }, { expireAfterSeconds: 3600 });

(3600 ) salesTime.

+3
source

All Articles