mongodb

【mongoDB】mongoDB如何删除表中所有数据?

2022-12-17  本文已影响0人  Bogon

方式1:db. 集合名 .remove({});

{}中不加条件,会直接逐条删除结合中所有数据,但是会保留索引,删除速度慢
适用于删除数据量小,且不想重建索引

如果数据量大,通过这种方式删除,可能会导致数据库堵塞,应用连接该库报timeout,此时应该:

  1. 停止删除语句/进程
  2. 手动触发主从切换

方式2: db. 集合名 .drop();

直接整个删除集合中所有数据,包括索引,删除速度快
如果再插入数据,需要 重建索引

mongoDB索引创建

testDB库,testColl表索引:

PRIMARY> db.testColl.getIndexes()

[
    {
        "v" : 2,
        "key" : {
            "_id" : 1
        },
        "name" : "_id_",
        "ns" : "testDB.testColl"
    },
    {
        "v" : 2,
        "key" : {
            "sendTime" : -1
        },
        "name" : "idx_sendTime",
        "ns" : "testDB.testColl",
        "background" : true
    },
    {
        "v" : 2,
        "key" : {
            "fromUserId" : 1,
            "sendTime" : -1,
            "msgType" : 1
        },
        "name" : "idx_fromUserId_sendTime_msgType",
        "ns" : "testDB.testColl",
        "background" : true
    },
    {
        "v" : 2,
        "key" : {
            "fromUserId" : 1,
            "sendTime" : -1,
            "groupType" : 1
        },
        "name" : "idx_fromUserId_sendTime_groupType",
        "ns" : "testDB.testColl",
        "background" : true
    },
    {
        "v" : 2,
        "key" : {
            "groupId" : 1
        },
        "name" : "idx_groupId",
        "ns" : "testDB.testColl",
        "background" : true
    }
]

转换为创建语句:

> use testDB

db.testColl.ensureIndex({"_id" : 1},{"background" : true})    // 默认就有,不需要手动创建

db.testColl.ensureIndex({"sendTime" : -1},{"background" : true})

db.testColl.ensureIndex({"fromUserId" : 1,"sendTime" : -1,"msgType" : 1},{"background" : true})

db.testColl.ensureIndex({"fromUserId" : 1,"sendTime" : -1,"groupType" : 1},{"background" : true})

db.testColl.ensureIndex({"groupId" : 1},{"background" : true})

参考

MongoDB 教程
https://www.jc2182.com/mongodb/mongodb-jiaocheng.html

上一篇 下一篇

猜你喜欢

热点阅读