Databases Reference
In-Depth Information
LISTING 2-2 (continued)
}
}
public void listAllCollections(String dbName) {
if(m!=null){
db = m.getDB(dbName);
Set<String> collections = db.getCollectionNames();
for (String s : collections) {
System.out.println(s);
}
}
}
public void listLocationCollectionDocuments() {
if(m!=null){
db = m.getDB(“prefs”);
DBCollection collection = db.getCollection(“location”);
DBCursor cur = collection.find();
while(cur.hasNext()) {
System.out.println(cur.next());
}
} else {
System.out.println(“Please connect to MongoDB
and then fetch the collection”);
}
}
public static void main(String[] args) {
ConnectToMongoDB connectToMongoDB = new ConnectToMongoDB();
connectToMongoDB.connect();
connectToMongoDB.listAllCollections(“prefs”);
connectToMongoDB.listLocationCollectionDocuments();
}
}
ConnectToMongoDB.java
Make sure to have the MongoDB Java driver in the classpath when you compile and run this
program. On running the program, the output is as follows:
location
system.indexes
{ “_id” : { “$oid” : “4c97053abe67000000003857”} , “name” : “John Doe” ,
“zip” : 10001.0}
{ “_id” : { “$oid” : “4c970541be67000000003858”} , “name” : “Lee Chang” ,
“zip” : 94129.0}
{ “_id” : { “$oid” : “4c970548be67000000003859”} , “name” : “Jenny Gonzalez” ,
“zip” : 33101.0}
Search WWH ::




Custom Search