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.
The limit() method in Mongoose is used to specify the number or a maximum number of documents to return from a query.
It's not mandatory to use Mongoose over the MongoDB Native API. However, there are some benefits to doing so.
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.
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.
MongoDB's remove operation doesn't support a limit option, but you can find
the _id
s 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)=> {...});
}
);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With