package lesson01
;
import com
.google
.gson
.Gson
;
import com
.mongodb
.MongoClient
;
import com
.mongodb
.client
.FindIterable
;
import com
.mongodb
.client
.MongoCollection
;
import com
.mongodb
.client
.MongoDatabase
;
import com
.mongodb
.client
.model
.Filters
;
import org
.bson
.Document
;
public class demo01_Connect_MongoDB {
public static void main(String
[] args
) {
CRUD crud
= new CRUD();
crud
.Find2();
}
static class CRUD {
public MongoCollection
<Document> connect() {
MongoClient client
= new MongoClient("localhost",27017);
MongoDatabase testDB
= client
.getDatabase("test");
MongoCollection
<Document> stuColl
= testDB
.getCollection("students");
return stuColl
;
}
public void Insert() {
MongoCollection
<Document> stuColl
= connect();
Student stu
= new Student("猪八戒", 28, "男");
Gson gson
= new Gson();
String stuJSON
= gson
.toJson(stu
);
Document doc
= Document
.parse(stuJSON
);
stuColl
.insertOne(doc
);
}
public void Find() {
MongoCollection
<Document> stuColl
= connect();
Document doc
= stuColl
.find().first();
Gson gson
= new Gson();
Student stu
= gson
.fromJson(doc
.toJson(), Student
.class);
System
.out
.println(stu
);
}
public void Find2() {
MongoCollection
<Document> stuColl
= connect();
FindIterable
<Document> docs
= stuColl
.find(Filters
.eq("name", "猪八戒"));
for (Document doc
: docs
) {
System
.out
.println(doc
.toJson());
}
}
public void Remove() {
MongoCollection
<Document> stuColl
= connect();
stuColl
.deleteOne(Filters
.eq("name", "猪八戒"));
}
public void updateOne() {
MongoCollection
<Document> stuColl
= connect();
stuColl
.updateOne(Filters
.eq("name", "猪八戒"), new Document("$set", new Document("age", 20)));
}
}
static class Student {
String name
;
int age
;
String gender
;
public Student(String name
, int age
, String gender
) {
this.name
= name
;
this.age
= age
;
this.gender
= gender
;
}
public String
getName() {
return name
;
}
public void setName(String name
) {
this.name
= name
;
}
public int getAge() {
return age
;
}
public void setAge(int age
) {
this.age
= age
;
}
public String
getGender() {
return gender
;
}
public void setGender(String gender
) {
this.gender
= gender
;
}
@Override
public String
toString() {
return "Student{" +
"name='" + name
+ '\'' +
", age=" + age
+
", gender='" + gender
+ '\'' +
'}';
}
}
}
转载请注明原文地址: https://mac.8miu.com/read-494925.html