7

如何获取数据库中所有集合的列表?

  • 数据库——mongodb;
  • 语言——java;
  • ide - 日食;
4

2 回答 2

19

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);
于 2011-02-11T16:15:20.553 回答
9

在 MongoDB 3 中,现在是db.listCollectionNames(). 还有db.listCollections()

请参阅API 文档

于 2015-11-19T00:09:46.160 回答