【问题标题】:Remove items with sort and limit in Mongodb [duplicate]在Mongodb中删除带有排序和限制的项目[重复]
【发布时间】:2018-10-24 03:08:58
【问题描述】:

我可以使用下一条 sql 语句删除 mysql 中最新的 10 项。

DELETE FROM `mytable` order by id desc limit 10

是否可以在 Mongodb 中使用 sort 和 limit 做同样的事情?

我知道如何找到最后 10 个项目

db.collection.find({}).sort("id", -1).limit(10)

但我不确定如何一步删除项目。

【问题讨论】:

    标签: mongodb pymongo


    【解决方案1】:

    您可以分两步完成:

    const ids = db.collection.find({})
                         .sort("id", -1)
                         .limit(10)
                         .toArray()
                         .map(ele => ele._id);
    
    db.collection.remove({_id: {$in: ids}})
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-02-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多