在我的Collection 中,文档包含类似键的状态和时间戳.当我想找到最新的十个文档时,我会写下面的查询
db.collectionsname.find().sort({"timestamp"-1}).limit(10)
这个查询给了我想要的结果,但是当我想删除最近的十个文档时,我写了下面的查询
db.collectionsname.remove({"status":0},10).sort({"timestamp":-1})
但它显示出以下错误
在我的Collection 中,文档包含类似键的状态和时间戳.当我想找到最新的十个文档时,我会写下面的查询
db.collectionsname.find().sort({"timestamp"-1}).limit(10)
这个查询给了我想要的结果,但是当我想删除最近的十个文档时,我写了下面的查询
db.collectionsname.remove({"status":0},10).sort({"timestamp":-1})
但它显示出以下错误
使用remove
或findAndModify
时不能设置限制.因此,如果想要精确地限制删除的文档数量,需要分两步进行.
db.collectionName.find({}, {_id : 1})
.limit(100)
.sort({timestamp:-1})
.toArray()
.map(function(doc) { return doc._id; }); // Pull out just the _ids
然后将返回的_id
传递给remove方法:
db.collectionName.remove({_id: {$in: removeIdsArray}})
仅供参考:您不能从封顶集合中删除文档.