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

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

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 @ 2022-03-23 14:23  panda4671  阅读(685)  评论(0编辑  收藏  举报