Mongo remove last documents

前端 未结 1 925
我寻月下人不归
我寻月下人不归 2020-12-29 09:28

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?

相关标签:
1条回答
  • 2020-12-29 10:04

    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.

    0 讨论(0)
提交回复
热议问题