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.
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.
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).
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.
Resolved it using this: db.offlineLogs.remove({"_ts":{"$lt":ISODate("2012-08-01T19:30:07.805Z")}});
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With