1 Import pakej pemacu Mongo
2 >3. Tutup pautan
MongoClient mc = new MongoClient("localhost",27017);
2. Lihat perpustakaan, lihat koleksi
mc.close();
2 perpustakaan
MongoDatabase db = mc.getDatabase("myschool");
3 , Java menambah, memadam dan mengubah suai MongoDB
MongoIterable<String> listCollectionNames = db.listCollectionNames(); MongoCursor<String> iterator = listCollectionNames.iterator(); while (iterator.hasNext()) { System.out.println(iterator.next()); }
2. Padamkan data
a . Ubah suai data
//创建对象 Student s = new Student(); s.setSid(1); s.setSname("王俊凯"); s.setBirthday(new Date()); s.setSsex("男"); s.setClassid(2); //将数据转换为json格式 Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd").create(); String json = gson.toJson(s); //获取集合对象 MongoCollection<Document> collection = db.getCollection("student"); //添加一条数据,将json格式转换为document对象 collection.insertOne(Document.parse(json));
b carian
//存入数据 List<Document> dlist=new ArrayList<Document>(); for(int i=0; i<3; i++){ Student s = new Student(); s.setSid(Integer.toString(i+1)); s.setSname("王源"); s.setBirthday(new Date()); s.setSsex("男"); s.setClassid(1); //将数据转换为json格式 Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd").create(); String json = gson.toJson(s); dlist.add(Document.parse(json)); } //获取集合对象 MongoCollection<Document> collection = db.getCollection("student"); //添加多条数据 collection.insertMany(dlist);
b. Pertanyaan dengan syarat
//获取集合对象 MongoCollection<Document> collection = db.getCollection("student"); Student s = new Student(); s.setSid(1); Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd").create(); Bson bson = Document.parse(gson.toJson(s)); DeleteResult deleteOne = collection.deleteOne(bson);
//获取集合对象 MongoCollection<Document> collection = db.getCollection("student"); Student s = new Student(); s.setSname("王源"); Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd").create(); Bson bson = Document.parse(gson.toJson(s)); DeleteResult deleteMany = collection.deleteMany(bson);
d
Atas ialah kandungan terperinci Contoh analisis kaedah biasa untuk menyambungkan MongoDB dalam Java. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!