SC_Chupacabra
SC_Chupacabra

Reputation: 14317

MongoDB - Remove Objects From Collection

How do I remove all but the first n objects from a collection in MongoDB? For example, I only want to keep the first 2000 objects in my collection, but at the moment, there are 15000 objects.

EDIT: My question is more generalized than this related question. Not a duplicate.

Upvotes: 1

Views: 1348

Answers (2)

Eleonora Ciceri
Eleonora Ciceri

Reputation: 1798

You could select the IDs of the first N documents (that you want to keep):

var ids = [];
db.collection.find().limit(N).toArray().map(function(doc){
    ids.push(doc._id);
});

Then, you perform the following query:

db.collection.remove({_id:{$nin:ids}})

This removes every tuple whose id is NOT in the array ids. For further information about $nin (i.e., "not in") operator see this link.

Upvotes: 2

jpaljasma
jpaljasma

Reputation: 1612

Have you considered capped collection with max parameter? https://docs.mongodb.org/manual/core/capped-collections/

db.createCollection("log", { capped : true, max : 2000 } );

If you really are just looking to delete all but 2000 newest objects, you could find the _id and remove everything $lt than _id.

Upvotes: 2

Related Questions