Get Collections from MongoDB in Java.
This example shows how to get collections from MongoDB in Java. Program to get list of all collection names in given mongodb database.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
import java.net.UnknownHostException; import java.util.Set; import com.mongodb.DB; import com.mongodb.DBCollection; import com.mongodb.Mongo; import com.mongodb.MongoException; public class GetCollectionApp { public static void main(String[] args) { try { Mongo mongo = new Mongo("localhost", 27017); DB db = mongo.getDB("yourdb"); // get entire list of collections Set collections = db.getCollectionNames(); for (String collectionName: collections) { System.out.println(collectionName); } // get a single collection DBCollection collection = db.getCollection("yourCollection"); System.out.println(collection.toString()); System.out.println("Done"); } catch (UnknownHostException e) { e.printStackTrace(); } catch (MongoException e) { e.printStackTrace(); } } } |