Connect to MongoDB using Java
Package mymaven; import java.net. unknownHostException; import java. util. set; import com. mongodb. basicDBObject; import com. mongodb. DB; import com. mongodb. DBCollection; import com. mongodb. DBCursor; import com. mongodb. DBObject; import com. mongodb. mongo; import com. mongodb. except exception; public class Test {/*** @ author ithomer.net * @ datetime 2013-11-11 */public static void main (String [] args) throws UnknownHostException, except exception {Mongo mongo = new Mongo ("172.27.9.104", 27017); // connect to the database DB = mongo. getDB ("mytestdb"); // database Set <String> cols = db. getCollectionNames (); // obtain all sets in the database (similar to tables in a relational database) // print out the set in the database, which should be nullfor (String s: cols) {System. out. println (s);} DBCollection collection = db. getCollection ("mytestcoll"); // creates a collection. drop (); // Delete the set. when data is inserted, BasicDBObject obj = new BasicDBObject () is automatically rebuilt; // initialize a basic DB object, and insert the database into the database as the DB object obj. put ("from", "blog.ithomer.net"); // put several key-value pairs (obj. put ("to", "forum.ithomer.net"); obj. put ("subject", "ithomer.net"); collection. insert (obj); // insert object DBObject dbobj = collection. findOne (); // view a record, findOne () = find (). limit (1); System. out. println (dbobj); // print the inserted data. // Insert 10 pieces of {ranking: I} data for (int I = 0; I <10; I ++) {collection. insert (new BasicDBObject (). append ("ranking", I);} System. out. println ("count:" + collection. getCount (); // print the total number of data in the Set DBCursor cursor = collection. find (); // then we use this cursor to traverse the set while (cursor. hasNext () {System. out. println (cursor. next ();} // simple condition query. query the records BasicDBObject whose ranking is 1 = new BasicDBObject (); query. put ("ranking", 1); cursor = collection. find (query); System. out. println ("collection find ({\" ranking \ ": 1}):"); while (cursor. hasNext () {System. out. println (cursor. next ();} // complex condition query. query records whose ranking value is greater than or equal to 5 and smaller than 9 = new BasicDBObject (); query. put ("ranking", new BasicDBObject ("$ gte", 5 ). append ("$ lt", 9); cursor = collection. find (query); System. out. println ("collection find ({\" ranking \ ": [5-9)}):"); while (cursor. hasNext () {System. out. println (cursor. next ();} // mongo. dropDatabase ("mytestdb"); // finally delete our test database }}
Running result:
mytestcollsystem.indexes{ "_id" : { "$oid" : "52c62ed8e4b0f4de3dd10107"} , "from" : "blog.ithomer.net" , "to" : "forum.ithomer.net" , "subject" : "ithomer.net"}count: 11{ "_id" : { "$oid" : "52c62ed8e4b0f4de3dd10107"} , "from" : "blog.ithomer.net" , "to" : "forum.ithomer.net" , "subject" : "ithomer.net"}{ "_id" : { "$oid" : "52c62ed8e4b0f4de3dd10108"} , "ranking" : 0}{ "_id" : { "$oid" : "52c62ed8e4b0f4de3dd10109"} , "ranking" : 1}{ "_id" : { "$oid" : "52c62ed8e4b0f4de3dd1010a"} , "ranking" : 2}{ "_id" : { "$oid" : "52c62ed8e4b0f4de3dd1010b"} , "ranking" : 3}{ "_id" : { "$oid" : "52c62ed8e4b0f4de3dd1010c"} , "ranking" : 4}{ "_id" : { "$oid" : "52c62ed8e4b0f4de3dd1010d"} , "ranking" : 5}{ "_id" : { "$oid" : "52c62ed8e4b0f4de3dd1010e"} , "ranking" : 6}{ "_id" : { "$oid" : "52c62ed8e4b0f4de3dd1010f"} , "ranking" : 7}{ "_id" : { "$oid" : "52c62ed8e4b0f4de3dd10110"} , "ranking" : 8}{ "_id" : { "$oid" : "52c62ed8e4b0f4de3dd10111"} , "ranking" : 9}collection find({"ranking":1}):{ "_id" : { "$oid" : "52c62ed8e4b0f4de3dd10109"} , "ranking" : 1}collection find({"ranking":[5-9)}):{ "_id" : { "$oid" : "52c62ed8e4b0f4de3dd1010d"} , "ranking" : 5}{ "_id" : { "$oid" : "52c62ed8e4b0f4de3dd1010e"} , "ranking" : 6}{ "_id" : { "$oid" : "52c62ed8e4b0f4de3dd1010f"} , "ranking" : 7}{ "_id" : { "$oid" : "52c62ed8e4b0f4de3dd10110"} , "ranking" : 8}
Source code download (maven)
Mongodb array example:
@ SuppressWarnings ("unchecked") public static void loadMediaTags (List <MediaEntity> mediaEntityList) {mediaEntityList. clear (); try {Mongo mongo = new Mongo (CosineCluster. g1__host, CosineCluster. g1__port); DB db = mongo. getDB (CosineCluster. gMongo_DB); DBCollection collection = db. getCollection (CosineCluster. g1__coll_media); DBCursor cursor = collection. find (); int index = 0; long startTime = System. currentTimeMillis (); while (cursor. hasNext () {BasicDBObject obj = (BasicDBObject) cursor. next (); long id = obj. getLong ("_ id"); ArrayList <String> tagList = (ArrayList <String>) obj. get ("tag"); // tagArrayList <String> keywordList = (ArrayList <String>) obj. get ("keyword"); // keywordArrayList <Integer> copyrightList = (ArrayList <Integer>) obj. get ("copyright"); // copyrightMediaEntity mediaEntity = new MediaEntity (); mediaEntity. setId (id); // tagfor (int j = 0; j <tagList. size (); j ++) {mediaEntity. addTag (tagList. get (j); int tagId = getTagInt (tagList. get (j); mediaEntity. addTag (tagId);} // actorsArrayList <DBObject> actorsObjList = (ArrayList <DBObject>) obj. get ("actors"); // actorsfor (int j = 0; j <actorsObjList. size (); j ++) {mediaEntity. addActor (String) actorsObjList. get (j ). get ("name"); int actorId = getActorInt (String) actorsObjList. get (j ). get ("name"); mediaEntity. addActor (actorId);} // directorArrayList <DBObject> directorObjList = (ArrayList <DBObject>) obj. get ("director"); // directorfor (int j = 0; j <directorObjList. size (); j ++) {mediaEntity. addDirector (String) directorObjList. get (j ). get ("name"); int directorId = getDirectorInt (String) directorObjList. get (j ). get ("name"); mediaEntity. addDirector (directorId);} // keywordfor (int j = 0; j <keywordList. size (); j ++) {mediaEntity. addKeyword (keywordList. get (j); int keywordId = getKeywordInt (keywordList. get (j); mediaEntity. addKeyword (keywordId);} // copyrightfor (int j = 0; j <copyrightList. size (); j ++) {mediaEntity. addCopyright (copyrightList. get (j);} mediaEntityList. add (mediaEntity); index ++; if (index> 100) {break;} System. out. println (index + "--- mediaEntity:" + mediaEntity. toString ();} long costTime = System. currentTimeMillis ()-startTime; System. out. println ("load data costTime =" + index + "; costTime =" + costTime/1000f);} catch (Exception e) {e. printStackTrace () ;}} public static int getTagInt (String tag) {int tagIntId =-1; try {login client mongo = new Login client (CosineCluster. g1__host, CosineCluster. g1__port); DB db = mongo. getDB (CosineCluster. gMongo_DB); DBCollection tagmapCollection = db. getCollection ("recommend_tag_map"); DBCursor cursor = tagmapCollection. find (new BasicDBObject ("name", tag); if (cursor = null | cursor. toArray (). size () <= 0) {// process the ing keyword smaller than 2 or n, the same as return tagIntId;} DBObject obj = cursor. toArray (). get (0); String name = tag; tagIntId = (Integer) obj. get ("id"); int num = (Integer) obj. get ("num"); mongo. close ();} catch (UnknownHostException e) {e. printStackTrace ();} return tagIntId;} public static int getActorInt (String actor) {int actorIntId =-1; try {login client mongo = new Login client (CosineCluster. g1__host, CosineCluster. g1__port); DB db = mongo. getDB (CosineCluster. gMongo_DB); DBCollection tagmapCollection = db. getCollection ("recommend_actor_map"); DBCursor cursor = tagmapCollection. find (new BasicDBObject ("name", actor); if (cursor = null | cursor. toArray (). size () <= 0) {return actorIntId;} DBObject obj = cursor. toArray (). get (0); String name = actor; actorIntId = (Integer) obj. get ("id"); int num = (Integer) obj. get ("num"); mongo. close ();} catch (UnknownHostException e) {e. printStackTrace ();} return actorIntId ;}
Getting started with Mongodb using Java