在Java中列出Mongo数据库中所有集合的列表

7

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

  • 数据库 - MongoDB;
  • 语言 - Java;
  • IDE - Eclipse;

在MongoDB的shell中,show collections就可以实现这个功能吗? - tonio
@tonio - OP特别询问了Java相关的问题。 - Gert
2个回答

19

获取集合列表 每个数据库都有零个或多个集合。您可以从db中检索它们的列表(并打印出其中存在的任何内容):

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

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

编辑:如@Andrew的回答所建议,更新的Java客户端使用此代码:

/**
 * 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();

并且基于文档类型获取可迭代的集合:

/**
 * 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);

9
在MongoDB 3中,现在是db.listCollectionNames()。还有db.listCollections()
请参见API文档

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接