如何在mongodb中删除N个文档 [英] 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})
,但显示以下错误
TypeError: Cannot call method 'sort' of undefined
再一次,我写了如下相同的查询
db.collectionsname.remove({"status":0},10)
它仅删除一个文档.那么,如何编写查询以删除十个最新文档并按时间戳排序?
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?
推荐答案
使用remove
或findAndModify
时无法设置限制.因此,如果要精确限制删除的文档数量,则需要分两个步骤进行.
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
然后将返回的_id
s传递到remove方法:
Then pass the returned _id
s to the remove method:
db.collectionName.remove({_id: {$in: removeIdsArray}})
仅供参考:您无法从有上限的集合中删除文档.
FYI: you cannot remove documents from a capped collection.
这篇关于如何在mongodb中删除N个文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!