Q:

How to delete rows within an interval in MongoDb

I have a collection with lot of rows, for instance:
{ "_id" : 1, "state" : "1+" }

I want to set up a cron tab in order to remove the first N rows in my collection.
I tried:
db.history.remove(
    {
        _id : 
        { 
            $lt : db.history.find().sort({_id:1}).limit(1)._id + N
        }
        , 
        $atomic : true 
    }
);

Where N is the number of rows to remove, and then I will add this string inside the --eval in my cron task, but this command return nothing.
What am I doing wrong? I can probably write a server side function with N in parameter...

A:

The following works for me:
for (var v = db.ninja.find().sort({_id:1}).limit(2);v.hasNext();) 
{
    db.ninja.remove(v.next());
}

Note:
1) Replace ninja with the name of your collection
2) variable v holds the cursor pointer to the sorted documents (sorted by _id). I have given a limit value of 2, you can replace it with the value of N

