1. Connect
① Way One
Mongoclientoptions.builder Builder = Mongoclientoptions.builder ();//various detailed configurations can be made through builderMongoclientoptions myoptions =Builder.build (); ArrayList<ServerAddress> serveraddresslist =NewArrayList (); ServerAddress Record=NewServerAddress ("localhost", 27017);//IP, PortServeraddresslist.add (record); //user name, default library name, passwordMongocredential credential = mongocredential.createcredential ("TestUser", "Test", "Testpwd". ToCharArray ()); Mongoclient mongoclient=NewMongoclient (serveraddresslist, credential, myoptions);
② Way Two
// user name, password, IP, port, default library name String SURI = String.Format ("Mongodb://%s:%[email protected]%s:%d/%s", "TestUser", "testpwd", "localhost", 27017, "test "); New Mongoclient (new Mongoclienturi (SURI));
③ mode three (can be used when permission verification mode is not enabled)
// login without user name and password (easy for beginners, avoid overly complex settings) New Mongoclient ("localhost", 27017);
2. Intermediate steps (Create a collection to store data, equivalent to table tables)
Mongodatabase dbTest = mongoclient.getdatabase ("test"); // If it does not exist, increase the collection Mongocollection<document> collection = Dbtest.getcollection ("test_collection"); if NULL { dbtest.createcollection ("test_collection"); }
3.insert
//Insert Add DataDocument doc =NewDocument (); Doc.append ("Name", "name1"); Doc.append ("Age", 20); //Collection.insertone (DOC);//add a piece of data//add more than one piece of dataDocument doc2 =NewDocument (); Doc2.append ("Name", "name2"); Doc2.append ("Age", 30); ArrayList dataList=NewArrayList (); Datalist.add (DOC); Datalist.add (DOC2); Collection.insertmany (dataList);
4.delete
// Delete Deletes data New Basicdbobject ("Name", "name1"); // Delete a bar // // Delete multiple strips
5.update
//Update modifies dataBasicdbobject Updateoldsql =NewBasicdbobject ("Name", "name2"); //update One piece of dataBasicdbobject Updatenewonesql =NewBasicdbobject ("$set",NewBasicdbobject ("Name", "name1")); //Collection.updateone (Updateoldsql,updatenewonesql); //update more than one dataBasicdbobject Updatenewmanysql =NewBasicdbobject ("$set",NewBasicdbobject ("Name", "name1"). Append ("Age", 66));//Modify multiple fieldsCollection.updatemany (Updateoldsql, updatenewmanysql);
6.query
// Querying Data New Basicdbobject ("Name", "name1"); Finditerable// Here you can do sort and filter operations mongocursor<document> cursor = Queryrst.iterator (); while (Cursor.hasnext ()) { System.out.println (Cursor.next ()); // output each row of data }
Above.
Java Operations MongoDB: Connect & Add & Delete & change & check