0

I can remove newest 10 items in mysql using my next sql statement.

DELETE FROM `mytable` order by id desc limit 10

Is it possible to do the same in Mongodb using sort and limit?

I know how to find last 10 items

db.collection.find({}).sort("id", -1).limit(10)

but I'm not sure how delete items in one step.

Dimitry
  • 359
  • 4
  • 13

1 Answers1

4

You can do it in two steps like this:

const ids = db.collection.find({})
                     .sort("id", -1)
                     .limit(10)
                     .toArray()
                     .map(ele => ele._id);

db.collection.remove({_id: {$in: ids}})
Tarek Essam
  • 3,602
  • 2
  • 12
  • 21