This article is relatively simple, only introduces the Java operation MongoDB Simple crud case, before you need to introduce Mongo-java-driver-3.2.2.jar,java operation MongoDB API many, advanced features also need to query official documents.
Public voidInsert () {//establishing a database connectionMongo Mongo =NewMongo ("localhost", 27017); //gets the specified databaseDB db = Mongo.getdb ("Kaiye"); //gets the specified collectionDbcollection DBC = db.getcollection ("C6"); //get actions and additions and changes to the objectDBObject dbo =NewBasicdbobject (); Dbo.put ("Name", "Zi Xuan"); Dbo.put ("Age", "22"); Dbc.insert (dbo); //Close Database LinkMongo.close (); System.out.println ("Insert Succeeded"); }
@Override Public voidDelete () {//establishing a database connectionMongo Mongo =NewMongo ("localhost", 27017); //gets the specified databaseDB db = Mongo.getdb ("Kaiye"); //gets the specified collectionDbcollection DBC = db.getcollection ("C5"); //get actions and additions and changes to the objectDBObject dbo =NewBasicdbobject (); Dbo.put ("Name", "Jumo"); Dbc.remove (dbo); //Close Database LinkMongo.close (); System.out.println ("Delete Succeeded"); }
@Override Public voidUpdate () {//establishing a database connectionMongo Mongo =NewMongo ("localhost", 27017); //gets the specified databaseDB db = Mongo.getdb ("Kaiye"); //gets the specified collectionDbcollection DBC = db.getcollection ("C4"); //get actions and additions and changes to the objectDBObject query =NewBasicdbobject ("Age", 7); DBObject Update=dbc.findone (query); Update.put ("Name", "Xuxuanli"); Dbc.update (query, update,true,true); //Close Database LinkMongo.close (); System.out.println ("Update succeeded"); }
@Override Public voidquery () {//establishing a database connectionMongo Mongo =NewMongo ("localhost", 27017); //gets the specified databaseDB db = Mongo.getdb ("Kaiye"); //gets the specified collectionDbcollection DBC = db.getcollection ("C6"); //get actions and additions and changes to the objectDBObject dbo =NewBasicdbobject (); //Query CriteriaDbo.put ("Age", "89"); //cursor QueryDbcursor dbcursor =dbc.find (dbo); //iterate through the result set to get the result returned while(Dbcursor.hasnext ()) {DBObject Dbo1=Dbcursor.next (); System.out.println (DBO1); } System.out.println ("Query succeeded"); }
Using Java to manipulate MongoDB