1, first download Mongodb-java-driver the latest version is 2.9.3
2. The following is the basic CRUD sample code:
1 PackageMongoDB;2 3 ImportCom.mongodb.BasicDBObject;4 ImportCom.mongodb.DB;5 Importcom.mongodb.DBCollection;6 ImportCom.mongodb.DBCursor;7 ImportCom.mongodb.DBObject;8 ImportCom.mongodb.Mongo;9 Importjava.net.UnknownHostException;Ten ImportJava.util.Set; One A Importorg.junit.Test; - - Public classTestmongodbdriver { the - @Test - Public voidTestcrud ()throwsunknownhostexception { - //Connect to MongoDB +Mongo Mongo =NewMongo ("localhost", 27017); - + //Open the database test ADB db = Mongo.getdb ("Test"); at - //iterate through the names of all the collections -Set<string> Colls =db.getcollectionnames (); - for(String s:colls) { - System.out.println (s); - //Delete all collection first (similar to "table" in relational database) in if(!s.equals ("System.indexes")) { - db.getcollection (s). Drop (); to } + } - the //Get Set EMP (if: EMP does not exist, MongoDB will automatically create the collection) *Dbcollection coll = db.getcollection ("emp"); $ Panax Notoginseng //Delete All -Dbcursor dbcursor =Coll.find (); the for(DBObject dbobject:dbcursor) { + Coll.remove (dbobject); A } the + //Create -Basicdbobject doc =NewBasicdbobject ("name", "Yang Junming"). Append ("Sex", "male") $. Append ("Address", $ NewBasicdbobject ("postcode", "201202"). Append ( -"Street", "No. No. 888 TianLin Road"). Append ("City", "Shanghai")); - Coll.insert (DOC); the - //RetrieveWuyiBasicdbobject DocFind =NewBasicdbobject ("name", "Yang Junming"); theDBObject Findresult =Coll.findone (docfind); - System.out.println (findresult); Wu - //Update AboutDoc.put ("Sex", "MALE");//Change the sex attribute from "male" to "MALE" $ coll.update (DocFind, doc); -Findresult =Coll.findone (docfind); - System.out.println (findresult); - AColl.dropindexes ();//Delete all indexes first + //CREATE INDEX theColl.createindex (NewBasicdbobject ("name", 1));//1 stands for ascending - } $ the}
View Code
Extended reading:
Mondodb-java-driver official online documentation
8-Day learning through MongoDB series
MongoDB Basic Usage