Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongo remove last documents

Tags:

mongodb

I would like to know how to delete, for example, the last 100 documents inserted in my collection.

How is it possible from the shell?

like image 355
ValentinH Avatar asked Jun 22 '13 21:06

ValentinH


1 Answers

You should be able to use the _id to sort on last inserted, as outlined in the answer here:

db.coll.find().sort({_id:-1}).limit(100);

It looks like using limit on the standard mongo remove operation isn't supported though, so you might use something like this to delete the 100 documents:

for(i=0;i<100;i++) {
    db.coll.findAndModify({query :{}, sort: {"_id" : -1}, remove:true})
}

See the docs for more on findAndModify.

like image 64
bcm360 Avatar answered Nov 07 '22 03:11

bcm360