mongodb Java SE 中连接 CRUD 菜鸟学习笔记

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);
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

江南一舟110

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值