Ionică Bizău
Ionică Bizău

Reputation: 113365

Remove a known number of documents from Mongo database

I have a very big database in Mongo. It has more than 69 000 documents.

I took the decision to remove the majority of them. I want to have just 10 documents, for example.

How can I randomly remove a number of documents from database inside of terminal (directly)?

I've already tried db.col_name.remove().limit(20) which is not working.

Upvotes: 0

Views: 58

Answers (1)

mpobrien
mpobrien

Reputation: 4962

There's no way to do this directly until https://jira.mongodb.org/browse/SERVER-1599 has been implemented.

As a workaround you can do the following. Basically, fetch a batch of _ids that you want to delete, and then do an additional .remove() call to actually delete them.

ids_to_remove = []
db.col.find({},{_id:1}).limit(100).forEach(function(doc){ids_to_remove.push(doc._id)});
db.col.remove({_id:{$in:ids_to_remove}})

Upvotes: 2

Related Questions