如何删除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:无法调用未定义的方法排序"
我再次写了与下面相同的查询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屋!