Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
116 views
in Technique[技术] by (71.8m points)

How to delete N numbers of documents in mongodb

In my collections, documents contains key like status and timestamp. When I want to find latest ten documents then I write following query

db.collectionsname.find().sort({"timestamp"-1}).limit(10)

This query gives me results which I want but when I want to delete latest ten documents then I was writing the following query

db.collectionsname.remove({"status":0},10).sort({"timestamp":-1})

but it shows following error TypeError: Cannot call method 'sort' of undefined and again I wrote the same query as below db.collectionsname.remove({"status":0},10) It deletes only one document. So how can I write a query which deletes ten latest documents and sorts on timestamp?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can't set a limit when using remove or findAndModify. So, if you want to precisely limit the number of documents removed, you'll need to do it in two steps.

db.collectionName.find({}, {_id : 1})
    .limit(100)
    .sort({timestamp:-1})
    .toArray()
    .map(function(doc) { return doc._id; });  // Pull out just the _ids

Then pass the returned _ids to the remove method:

db.collectionName.remove({_id: {$in: removeIdsArray}})

FYI: you cannot remove documents from a capped collection.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...