Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove old records in mongodb

I have records of the following type 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 do I remove old records? I have tried something like db.offlineLogs.remove({timestamp: {$lt:new Date("2012, 8, 3")}});, but it doesn't work.

like image 323
ddd Avatar asked Aug 07 '12 20:08

ddd


People also ask

How do I remove all records from a collection in MongoDB?

To delete all documents in a collection, pass an empty document ( {} ). Optional. To limit the deletion to just one document, set to true . Omit to use the default value of false and delete all documents matching the deletion criteria.

How do I delete a file in MongoDB after time?

TTL index. TTL (Time-To-Live) indexes are special single-field indexes that MongoDB can use to automatically remove documents from a collection after a certain amount of time. A background thread in mongod reads the values in the index and removes expired documents from the collection (usually every minute).

Which function removes collection in MongoDB?

The remove() Method MongoDB's remove() method is used to remove a document from the collection. remove() method accepts two parameters. One is deletion criteria and second is justOne flag. deletion criteria − (Optional) deletion criteria according to documents will be removed.


2 Answers

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

like image 93
ddd Avatar answered Sep 28 '22 10:09

ddd


You might also check on using TimeToLive.

MongoDB has a feature TimeToLive where you can specify how long you would like a document to be present in a collection before it is automatically deleted.

For example, assume you have a collection named billing with the following fields:

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

You can create a index on this collection like:

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

This will make any document in the collection to be deleted after one hour (3600 seconds) based on the salesTime field.

like image 35
samo Avatar answered Sep 28 '22 08:09

samo