截断一个集合

ief*_*fpw 52 mongodb mongodb-.net-driver

如何截断MongoDB中的集合或者是否有这样的东西?

现在我必须一次删除6个大型集合,我将停止服务器,删除数据库文件,然后重新创建数据库及其中的集合.有没有办法删除数据并保留集合原样?删除操作需要很长时间.我在馆藏中有数百万条.

ast*_*anu 62

截断集合并保持索引的使用

 db.<collection>.remove({})
Run Code Online (Sandbox Code Playgroud)

  • @astroanu 是的,当然。上次我用 remove() 删除了 150 亿个文档,花了很长时间……实际上,长得令人无法接受。所以 drop() 、 createCollection() 和 createIndex() 是截断操作的唯一方法。 (2认同)

Ste*_*nie 39

您可以有效地删除集合的所有数据和索引db.collection.drop().删除包含大量文档和/或索引的集合将比使用删除所有文档更有效db.collection.remove({}).该remove()方法在删除文档时执行更新索引的额外内务处理,并且在副本集环境中甚至更慢,其中oplog将包括删除的每个文档的条目而不是单个集合删除命令.

使用mongoshell的示例:

var dbName = 'nukeme';
db.getSiblingDB(dbName).getCollectionNames().forEach(function(collName) {
    // Drop all collections except system ones (indexes/profile)
    if (!collName.startsWith("system.")) {
        // Safety hat
        print("WARNING: going to drop ["+dbName+"."+collName+"] in 5s .. hit Ctrl-C if you've changed your mind!");
        sleep(5000);
        db[collName].drop();
    }
})
Run Code Online (Sandbox Code Playgroud)

值得注意的是,根据配置的存储引擎,删除集合会对存储使用产生不同的结果:

  • 一旦删除完成,WiredTiger(MongoDB 3.2或更新版本中的默认存储引擎)将释放已删除集合(以及任何关联索引)使用的空间.
  • MMAPv1(MongoDB 3.0及更早版本中的默认存储引擎) 不会释放预分配的磁盘空间.这对您的用例可能没问题; 插入新数据时,可以重用可用空间.

如果您正在删除数据库,则通常不需要显式创建集合,因为它们将在插入文档时创建.

但是,这是一个在mongoshell 中删除和重新创建具有相同集合名称的数据库的示例:

var dbName = 'nukeme';

// Save the old collection names before dropping the DB
var oldNames = db.getSiblingDB(dbName).getCollectionNames();

// Safety hat
print("WARNING: going to drop ["+dbName+"] in 5s .. hit Ctrl-C if you've changed your mind!")
sleep(5000)

db.getSiblingDB(dbName).dropDatabase();

// Recreate database with the same collection names
oldNames.forEach(function(collName) {
    db.getSiblingDB(dbName).createCollection(collName);
})
Run Code Online (Sandbox Code Playgroud)


Cha*_*ist 17

remove() is deprecated in MongoDB 4.

You need to use deleteMany or other functions:

db.<collection>.deleteMany({})
Run Code Online (Sandbox Code Playgroud)


IAm*_*mes 9

以下查询将删除集合中的所有记录,并将按原样保留集合,

db.collectionname.remove({})
Run Code Online (Sandbox Code Playgroud)


Alo*_*lon 5

MongoDB 中没有与“截断”操作等效的操作。您可以删除所有文档,但它的复杂度为 O(n),或者删除集合,那么复杂度将为 O(1),但您将丢失索引。