ief*_*fpw 52 mongodb mongodb-.net-driver
如何截断MongoDB中的集合或者是否有这样的东西?
现在我必须一次删除6个大型集合,我将停止服务器,删除数据库文件,然后重新创建数据库及其中的集合.有没有办法删除数据并保留集合原样?删除操作需要很长时间.我在馆藏中有数百万条.
ast*_*anu 62
截断集合并保持索引的使用
db.<collection>.remove({})
Run Code Online (Sandbox Code Playgroud)
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)
值得注意的是,根据配置的存储引擎,删除集合会对存储使用产生不同的结果:
如果您正在删除数据库,则通常不需要显式创建集合,因为它们将在插入文档时创建.
但是,这是一个在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)
| 归档时间: |
|
| 查看次数: |
59682 次 |
| 最近记录: |