I am a newbie in database projects. I don't know how to display a collection in mongodb inside a swing window (EDIT: JTable) after connecting it to the database server....plz help me out in this... I have tried doing this in sql but am not able to do using mongodb
JButton btnDisplay = new JButton("display");
btnDisplay.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
// To connect to mongodb server
MongoClient mongoClient = new MongoClient( "localhost" , 27017 );
// Now connect to your databases
DB db = mongoClient.getDB( "test" );
System.out.println("Connect to database successfully");
DBCollection coll = db.getCollection("cars");
DBCursor cursor = coll.find();
}
catch (Exception a) {
a.printStackTrace();
}
}
});
DBCursor is meant to be iterated through. You can use the
DBCursor#hasNext()
like you would a normalIterator
, and theDBCursor#next()
to get the nextDBObject
. TheDBObject
allows you toget
values like you would aMap
, by passing in the keySo let's say we have a collection
table
in theswingtest
database, with the following documentsYou haven't actually specified what you want to do with the collection, so let's say you want to add the data to a
JTable
, you could do something likewhere for each iteration (document), we get the
_id
,first
andlast
values, then create a row in which we add theDefaultTableModel
. At the end of the iterating, we set the model for theJTable
.Here's the full example
Resource