mongodb Java 连接 CRUD 菜鸟学习笔记
###1.加载驱动
国内 mongodb-driver jar 下载地址:http://central.maven.org/maven2/org/mongodb/mongo-java-driver/
###2.Java连接
ServerAddress serverAddress = new ServerAddress("IP", 27017);
//MongoCredential.createScramSha1Credential()三个参数分别为 用户名 数据库名称 密码
MongoCredential credential = MongoCredential.createScramSha1Credential("root", "admin", "123456".toCharArray());
//通过连接认证获取MongoDB连接
MongoClient mongoClient = new MongoClient(Arrays.asList(serverAddress), Arrays.asList(credential));
//连接到数据库
MongoDatabase mongoDatabase = mongoClient.getDatabase("student");
// mongoDatabase.createCollection("test");
MongoCollection<Document> documentMongoCollection = mongoDatabase.getCollection("test");
在这里插入代码片
3.CRUD垃圾模版代码
在这里插入代码片
### private static void deleteDoc(MongoCollection<Document> documentMongoCollection) {
documentMongoCollection.deleteMany(Filters.gt("age",20));
}
private static void updateDoc(MongoCollection<Document> documentMongoCollection) {
documentMongoCollection.updateMany(Filters.eq("age",25),new Document("$set",new Document("age",20)));
}
private static void selectData(MongoCollection<Document> documentMongoCollection) {
FindIterable<Document> documents = documentMongoCollection.find();
MongoCursor<Document> iterator = documents.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
}
private static void add(MongoCollection<Document> documentMongoCollection) {
List<Document> docs = new ArrayList<>();
// Document document=new Document().append("name","fyd");
Map<String, Object> maps = new HashMap<>();
maps.put("name", "test");
maps.put("age", 30);
docs.add(new Document(maps));
documentMongoCollection.insertMany(docs);
}