简体   繁体   中英

How to remove except latest 10 record using Mongodb or mongoose lib?

I'm using this query:

db.date.remove({
    _id:{ $not:{ $eq: ObjectId("570ba4f66931b8f21a8bf25f") }},
    date:{ $lt: outdated }
})

But it is not working properly. I don't need to give ids.

How to remove (delete) except latest 10 record?

It can be done by iterating on the sorted list of collection and you can continue for 10 or specified N records and then delete after it as db.collectionName.remove({_id:ObjectId(<IteratorID>)})

Let us see in the details from inserting the records and then proof of concept for deleting it

Inserting 19 records in a collection st2 (just for checking the correctness of the script) in mongo shell:

> for(var i =1; i<20;i++) { db.st2.insert({"a":i}) }
> 

Some of the records look likes as:

> db.st2.find()
{ "_id" : ObjectId("5c62e71d6ddb127f4e87dfc4"), "a" : 1 }
{ "_id" : ObjectId("5c62e7476ddb127f4e87dfc5"), "a" : 2 }
...
...

Just to iterate and print the values which will be deleted [This is only for script verification purposes]

> var counter = 0;
> var allRecords = db.st2.find().sort({ "_id" : -1});
> var totalElements= allRecords.count()
> for(var i = 0; i<totalElements; i++) { if (i<=10) {allRecords.next();continue;} var currentRecord = allRecords.next(); print(currentRecord._id); print(currentRecord.a)};
ObjectId("5c62e7476ddb127f4e87dfcb")
8
ObjectId("5c62e7476ddb127f4e87dfca")
7
ObjectId("5c62e7476ddb127f4e87dfc9")
6
....
....

In the place of printing the records with id, just delete it as db.collectionName.remove({_id:currentRecord._id}) check it below:

> var allRecords = db.st2.find().sort({ "_id" : -1});
> 
> var totalElements= allRecords.count()
> totalElements
19
> for(var i = 0; i<totalElements; i++) { if (i<=10) {allRecords.next();continue;} var currentRecord = allRecords.next(); db.st2.remove({_id:currentRecord._id});};
WriteResult({ "nRemoved" : 1 })
> var totalElements= allRecords.count()
> totalElements
11
>

Its deleted the older records and only left 11 records. just check the if condition and you can exactly left with N records or whatever you want.

Hope this will help you to understand it in better way, since I tried to cover it with full details so that you or someone might get benefited with these examples.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM