List of all collections in mongo database in java

不问归期 提交于 2020-06-27 09:08:56

问题


how can I get a list of all the collections in the database?

  • database - mongodb;
  • language - java;
  • ide - eclipse;

回答1:


Getting A List Of Collections Each database has zero or more collections. You can retrieve a list of them from the db (and print out any that are there) :

Set<String> colls = db.getCollectionNames();

for (String s : colls) {
System.out.println(s);
}

Edit : As suggested in @Andrew's answer, updated java client uses this :

/**
 * Gets the names of all the collections in this database.
 *
 * @return an iterable containing all the names of all the collections in this database
 */
MongoIterable<String> listCollectionNames();

and getting the iterable collection based on the document type :

/**
 * Finds all the collections in this database.
 *
 * @param resultClass the class to decode each document into
 * @param <TResult>   the target document type of the iterable.
 * @return the list collections iterable interface
 * @mongodb.driver.manual reference/command/listCollections listCollections
 */
<TResult> ListCollectionsIterable<TResult> listCollections(Class<TResult> resultClass);



回答2:


In MongoDB 3, it's now db.listCollectionNames(). There's also db.listCollections()

See the API Docs.



来源:https://stackoverflow.com/questions/4971329/list-of-all-collections-in-mongo-database-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!