Searching...
Tuesday, 18 September 2012

Java MongoDB Retrieve Collection details from Mongodb

23:56

How to retrieve collection details from Mongo db?

package com.vinod.examples;

import java.net.UnknownHostException;
import java.util.Set;

import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.Mongo;

public class RetriveCollections {

    public static void main(String[] args) {
    try {

        Mongo mongo = new Mongo("localhost", 27017);
        DB db = mongo.getDB("customerdb");

        // Retrieve list of collections/Tables
        Set<String> collections = db.getCollectionNames();

        for (String collectionName : collections) {
        System.out.println("Collection names " + collectionName);
        }

        // get a single collection
        DBCollection collection = db.getCollection("customer");
        System.out.println(collection.toString());

    } catch (Exception e) {
        e.printStackTrace();
    }
    }

}
 

Output

Collection names customer

Collection names customerCollection

Collection names customerDetails

Collection names system.indexes

DBCollection{database=DB{name='customerdb'}, name='customer'}

0 comments: