Created
July 13, 2014 09:04
-
-
Save mh-github/c2b26273442702f2a9b8 to your computer and use it in GitHub Desktop.
Fetch records from MongoDB and print them
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import com.mongodb.MongoClient; | |
| import com.mongodb.MongoException; | |
| import com.mongodb.WriteConcern; | |
| import com.mongodb.DB; | |
| import com.mongodb.DBCollection; | |
| import com.mongodb.BasicDBObject; | |
| import com.mongodb.DBObject; | |
| import com.mongodb.DBCursor; | |
| import com.mongodb.ServerAddress; | |
| import java.util.Arrays; | |
| public class Mongo_Retrieve_Collection | |
| { | |
| public static void main( String args[] ) | |
| { | |
| try { | |
| // To connect to mongodb server | |
| MongoClient mongoClient = new MongoClient( "localhost" , 27017 ); | |
| // Now connect to your databases | |
| DB db = mongoClient.getDB( "mh-db" ); | |
| System.out.println("Connect to database successfully"); | |
| DBCollection collection = db.getCollection("mhColl"); | |
| System.out.println("Collection mhColl selected successfully"); | |
| System.out.println("Retrieving and printing the records"); | |
| long time1 = System.currentTimeMillis(); | |
| DBCursor cursor = collection.find(); | |
| while (cursor.hasNext()) { | |
| System.out.println(cursor.next()); | |
| } | |
| long time2 = System.currentTimeMillis(); | |
| System.out.println("------------------"); | |
| System.out.println("Retrieving and printing took " + (time2 - time1) + " ms"); | |
| } | |
| catch (Exception e){ | |
| System.err.println( e.getClass().getName() + ": " + e.getMessage() ); | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment