mongodb 如何删除mongodb中的N个文档

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19065615/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 13:26:12  来源:igfitidea点击:

How to delete N numbers of documents in mongodb

mongodb

提问by Yogesh

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 undefinedand 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?

但它显示以下错误 TypeError: Cannot call method 'sort' of undefined,我再次编写了与下面相同的查询 db.collectionsname.remove({"status":0},10)它只删除了一个文档。那么如何编写一个删除十个最新文档并按时间戳排序的查询呢?

回答by WiredPrairie

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

使用remove或时不能设置限制findAndModify。因此,如果您想精确限制删除的文档数量,则需要分两步完成。

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:

然后将返回的_ids传递给 remove 方法:

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

FYI: you cannot remove documents from a capped collection.

仅供参考:您不能从有上限的集合中删除文档。

回答by deusxmachine

Let N be number of records to delete.

设 N 为要删除的记录数。

    db.collectionName.find().limit(N).forEach(doc => 
     { 
       db.collectionName.remove({_id:doc._id})
     }
    )

回答by Manoj Pandey

To remove N number of documents in your collection myCollection:

要删除集合中的 N 个文档myCollection

db.getCollection('myCollection').find({}).limit(N).forEach(function(doc){
    db.getCollection('myCollection').remove({_id: doc._id});
})

回答by Anthony Awuley

db.collection.remove({_id: 
    { $in: db.collection.find().sort({timestamp:-1}).limit(100).map(a => a._id) }
})

回答by jellyDean

Another way is to write a python script.

另一种方法是编写python脚本。

from pymongo import MongoClient

def main():
    local_client = MongoClient()
    collection = local_client.database.collection
    cursor = collection.find()
    total_number_of_records = 10000

    for document in cursor:
        id = document.get("_id")

        if total_number_of_records == 100:
            break

        delete_query = {"_id": id}
        collection.delete_one(delete_query)

        total_number_of_records -= 1

if __name__ == "__main__":
    # execute only if run as a script
    main()

回答by yitai wei

query sql is

查询sql是

db.order.find({"业务员姓名" : "吊炸天"},{"业务员编号":0}).sort({ "订单时间" : -1 })

the result is

结果是

{
"_id" : ObjectId("5c9c875fdadfd961b4d847e7"),
"推送ID" : "248437",
"订单时间" : ISODate("2019-03-28T08:35:52Z"),
"订单状态" : "1",
"订单编号" : "20190328163552306694",
"业务员姓名" : "吊炸天"
}
{
"_id" : ObjectId("5c9c875fdadfd961b4d847e8"),
"推送ID" : "248438",
"订单时间" : ISODate("2019-03-28T08:35:52Z"),
"订单状态" : "1",
"订单编号" : "20190328163552178132",
"业务员姓名" : "吊炸天"
}
{
"_id" : ObjectId("5c9c875fdadfd961b4d847e5"),
"推送ID" : "248435",
"订单时间" : ISODate("2019-03-28T08:35:51Z"),
"订单状态" : "1",
"订单编号" : "20190328163551711074",
"业务员姓名" : "吊炸天"
}
{
"_id" : ObjectId("5c9c875fdadfd961b4d847e6"),
"推送ID" : "248436",
"订单时间" : ISODate("2019-03-28T08:35:51Z"),
"订单状态" : "1",
"订单编号" : "20190328163551758179",
"业务员姓名" : "吊炸天"
}

now delete the 3 and 4 data

现在删除3和4数据

var name = ["吊炸天"]
var idArray = db.order.find({"业务员姓名" : {$in:name}},{"订单编号":1,})
                .sort({ "订单时间" : -1 })
                .skip(2)
                .map(function(doc){return doc.订单编号})

db.order.deleteMany({"订单编号":{$in:idArray}})

return result is

返回结果是

{
"acknowledged" : true,
"deletedCount" : 2
}

回答by Pratiksha Aggarwal

Below query will find and delete the latest 10 documents from collection:-

以下查询将从集合中查找并删除最新的 10 个文档:-

db.collectionsname.findAndModify({
    query: { 'status':0 },
    sort: { 'timestamp': -1 },
    limit: 10,
    remove: true
});