如何用正则表达式筛选名称含'tnt'的MongoDB数据库列表
筛选包含特定字符串的MongoDB数据库
很简单,你只需要在遍历数据库列表的时候,加一个条件判断来过滤名称包含'tnt'的库就行。这里有两种常用写法:
方法一:在forEach里直接判断
修改你原来的代码,加入includes()方法做字符串匹配:
db.adminCommand("listDatabases").databases.forEach(function(d) { // 检查数据库名称是否包含'tnt'子串 if (d.name.includes('tnt')) { print(d.name); } });
如果需要忽略大小写(比如匹配'TNT'或'Tnt'),可以把名称转成小写后再判断:
db.adminCommand("listDatabases").databases.forEach(function(d) { if (d.name.toLowerCase().includes('tnt')) { print(d.name); } });
方法二:先过滤再遍历(更简洁)
用filter()先把符合条件的数据库筛选出来,再遍历打印,逻辑更直观:
// 先筛选出名称含'tnt'的数据库,再逐个打印名称 db.adminCommand("listDatabases").databases .filter(d => d.name.includes('tnt')) .forEach(d => print(d.name));
这两种方法都能帮你得到想要的结果:customer1_tnt1和customer2_tnt1。
内容的提问来源于stack exchange,提问作者Uliysess
相关产品推荐
相关产品推荐

