Created
June 4, 2015 16:30
-
-
Save rhulha/8e0912c5f7a3bc68128e to your computer and use it in GitHub Desktop.
MongoDB Hello World
This file contains 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
package com.mkyong.core; | |
import java.net.UnknownHostException; | |
import java.util.Date; | |
import com.mongodb.BasicDBObject; | |
import com.mongodb.DB; | |
import com.mongodb.DBCollection; | |
import com.mongodb.DBCursor; | |
import com.mongodb.MongoClient; | |
import com.mongodb.MongoException; | |
/** | |
* Java + MongoDB Hello world Example | |
* | |
*/ | |
public class App { | |
public static void main(String[] args) { | |
try { | |
/**** Connect to MongoDB ****/ | |
// Since 2.10.0, uses MongoClient | |
MongoClient mongo = new MongoClient("localhost", 27017); | |
/**** Get database ****/ | |
// if database doesn't exists, MongoDB will create it for you | |
DB db = mongo.getDB("testdb"); | |
/**** Get collection / table from 'testdb' ****/ | |
// if collection doesn't exists, MongoDB will create it for you | |
DBCollection table = db.getCollection("user"); | |
/**** Insert ****/ | |
// create a document to store key and value | |
BasicDBObject document = new BasicDBObject(); | |
document.put("name", "mkyong"); | |
document.put("age", 30); | |
document.put("createdDate", new Date()); | |
table.insert(document); | |
/**** Find and display ****/ | |
BasicDBObject searchQuery = new BasicDBObject(); | |
searchQuery.put("name", "mkyong"); | |
DBCursor cursor = table.find(searchQuery); | |
while (cursor.hasNext()) { | |
System.out.println(cursor.next()); | |
} | |
/**** Done ****/ | |
System.out.println("Done"); | |
} catch (UnknownHostException e) { | |
e.printStackTrace(); | |
} catch (MongoException e) { | |
e.printStackTrace(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment