Addition, deletion, modification and query (CRUD) of Java operation MongoDB database
1. Download the driver https://github.com/mongodb/mongo-java-driver/downloads and import it into the project java 2, build test code 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.MongoException; public class TestMain { public static void main(String[] args) throws UnknownHostException, MongoException { // Mongo m = new Mongo();//default local // Mongo m = new Mongo(“192.168.0.101”);//Default port Mongo m = new Mongo(“192.168.0.101”,27017); //Get the database named alan, create it if it does not exist DB db = m. getDB(“alan”); //Get all databases, do not display db without collection System.out.println(“All database names: “+m.getDatabaseNames()); //Get the collection named testCollection (equivalent to a table), and create it if it does not exist DBCollection coll = db.getCollection(“testCollection”); //Insert value into collection (insert can be inserted) BasicDBObject obj = new BasicDBObject(); obj.put(“name”,”jone”); obj.put(“sex”, “male”); BasicDBObject info = new BasicDBObject(); info.put(“height”, 172); info.put(“weight”, 65); obj.put(“other”, info); coll.insert(obj); //Get all collections under the database, do not display collections without data Set colls = db.getCollectionNames(); for(String s : colls){ System.out.println(s); } //Query all records in coll DBCursor ite = coll. find(); while(ite.hasNext()){ System.out.println(ite.next()); } //Get the first record DBObject o = coll. findOne(); System.out.println(o); “ //Statistics of the number of colletion data System.out.println(coll.getCount()); //…