Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List of all collections in mongo database in java

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

  • database - mongodb;
  • language - java;
  • ide - eclipse;
like image 975
Saska Avatar asked Feb 11 '11 16:02

Saska


People also ask

How do I get a list of databases in MongoDB?

If you want to check your databases list, use the command show dbs. Your created database (mydb) is not present in list. To display database, you need to insert at least one document into it. In MongoDB default database is test.

How do I find the number of collections in MongoDB?

n = count( conn , collection ) returns the total number of documents in a collection by using the MongoDB® C++ interface connection. n = count( conn , collection ,Query= mongoquery ) returns the total number of documents in an executed MongoDB query on a collection.

What is the command for listing all collections in a database?

If you're using the mongo shell, the quickest way to get a list of collections is to use the show collections command. This command retrieves a list of collections and views in the current database.


2 Answers

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);
like image 185
reggie Avatar answered Nov 18 '22 13:11

reggie


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

See the API Docs.

like image 29
Andrew Avatar answered Nov 18 '22 12:11

Andrew