Java获取mongo所有的collection及collection column/field名称

下列为获取mongodb中所有的collection(table)和 column(field)名称的java实现。已测试通过。我这里获取连接是用的getURL().具体的连接写法参见之前的连接mongodb的三种方式。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public void getMongoCollectionsAndFields() {
        MongoClient mongoClient = new MongoClient(new MongoClientURI(getURL()));
        MongoDatabase db = mongoClient.getDatabase(db_name);
        MongoIterable<Document> collections = db.listCollections();
        for (Document collectionname : collections) {
            System.out.println(collectionname);
            String table_name = collectionname.getString("name");
            MongoCollection<Document> collection = db.getCollection(table_name);
            if (!table_name.contains("system.views")) {
                Document doc = collection.find().first();
                if (doc == null)
                    return;
                for (Map.Entry<String, Object> entry : doc.entrySet()) {
                    if (!entry.getKey().startsWith("_")) {
                        System.out.println(entry.getKey() + "    " + entry.getValue());
                    }
                }
            }
        }
        mongoClient.close();
    }

  

 

posted @   panda4671  阅读(700)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
点击右上角即可分享
微信分享提示