1

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.

1

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Nice solution. Thanks :)
2

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.

5 Comments

At that point he would have something not fully manageable. Notice that you cannot delete documents from a capped collection! That would be a fixed size collection.
And you are right. However, user asked: I only want to keep the first 2000 objects in my collection - hence capped collection.
Yes, I agree. Your solution works fine if then that collection is (allowed me the term) "dead", i.e., he won't modify its size. If he wants to do something more -after- the shrinking, then another solution may be needed.
In this case, Eleanore is right. The collection isn't set-in-stone so to speak, but I appreciate the extra suggestion (and I learned something in the process).
This is exactly what I was looking for here, I just didn't know the term. Thank you!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.