Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Limit is ignored when remove (mongoose)

I need to remove the earliest several documents in a collection, so I wrote something like this:

Model.remove({
    u: "abc"
}).sort({
    _id: 1
}).limit(10).exec(function (err, count) {
    // count gives the total documents number...
});

And this:

Model.find(...).sort(...).limit(...).remove(...);

Hoping someone would help. Thanks.

like image 727
vilicvane Avatar asked Mar 19 '14 15:03

vilicvane


People also ask

What does limit do in Mongoose?

The limit() method in Mongoose is used to specify the number or a maximum number of documents to return from a query.

Is it mandatory to use Mongoose with Node application?

It's not mandatory to use Mongoose over the MongoDB Native API. However, there are some benefits to doing so.

What does Mongoose deleteMany return?

The deleteMany() method returns an object that contains three fields: n – number of matched documents. ok – 1 if the operation was successful. deletedCount – number of deleted documents.

What is the Mongoose command used to delete an item?

There are a few different ways to perform delete operations in Mongoose: deleteOne() to delete a single document, deleteMany() to delete multiple documents and remove() to delete one or multiple documents.


2 Answers

MongoDB's remove operation doesn't support a limit option, but you can find the _ids of the docs you want to remove, and then use $in to remove them:

Model.find({u: "abc"}).select('_id').sort({_id: 1}).limit(10)
    .exec((err, docs)=> {
        const ids = docs.map((doc)=> doc._id);
        Model.deleteMany({_id: {$in: ids}}, (err)=> {...}); 
    }
);
like image 114
JohnnyHK Avatar answered Sep 30 '22 13:09

JohnnyHK


db.collection.remove() doesn't return a cursor. So, you cannot append cursor methods like sort() or limit(), like you can to a db.collection.find() operation.

You might want to look at db.collection.findAndModify(), to which you can supply a remove parameter to delete a document.

like image 34
Anand Jayabalan Avatar answered Sep 30 '22 14:09

Anand Jayabalan