为了账号安全,请及时绑定邮箱和手机立即绑定

MongoDB十分钟搞定CRUD

标签:
MongoDB

一、环境准备
MongoDB环境安装参照 MongoDBWindows平台安装
二、创建项目,添加MongoDB驱动依赖Jar

<dependency>
    <groupId>org.mongodb</groupId>
    <artifactId>mongo-java-driver</artifactId>
    <version>3.4.0</version>
</dependency>

三、创建连接

// To directly connect to a single MongoDB server
// (this will not auto-discover the primary even if it's a member of a replica set)
MongoClient mongoClient = new MongoClient();

// or
MongoClient mongoClient = new MongoClient( "localhost" );

// or
MongoClient mongoClient = new MongoClient( "localhost" , 27017 );

// or, to connect to a replica set, with auto-discovery of the primary, supply a seed list of members
MongoClient mongoClient = new MongoClient(
  Arrays.asList(new ServerAddress("localhost", 27017),
                new ServerAddress("localhost", 27018),
                new ServerAddress("localhost", 27019)));

// or use a connection string
MongoClientURI connectionString = new MongoClientURI("mongodb://localhost:27017,localhost:27018,localhost:27019");
MongoClient mongoClient = new MongoClient(connectionString);

MongoDatabase database = mongoClient.getDatabase("mydb");

这是驱动api提供的几种连接数据库的方式,选一个自己喜欢的即可
四、开始CRUD

  • insert
    这里先插入一点点数据方便后面测试
        MongoClient mongoClient = new MongoClient( "localhost" , 27017 );
        MongoDatabase mongoDatabase = mongoClient.getDatabase("dbtest"); 
        MongoCollection<Document> collection = mongoDatabase.getCollection("users");
        for (int i = 0; i < 100000; i++) {
                Document document=  new Document();
                document.append("name", "white"+i);
                document.append("age",i);
                document.append("sex",i%2);
                document.append("money",i*10);
                // insert into users(....)
                collection.insertOne(document);
        } 
        mongoClient.close();
  • query
    ①条件查询
    @Test
    public void findByCondition(){
        MongoClient mongoClient = new MongoClient( "localhost" , 27017 );
        MongoDatabase db = mongoClient.getDatabase("dbtest"); 
        MongoCollection<Document> collection = db.getCollection("users");
        // select * from user
        collection.find();
        // select top 1 * from user where name = 'white11'
        collection.find(Filters.eq("name", "white11")).first();
        // select * from user where age < 10
        collection.find(Filters.lt("age", 10));
        // select * from user where age>= 70 and age<=100
        collection.find(Filters.and(Filters.lte("age", 100),Filters.gte("age", 70)));
        mongoClient.close();
    }
②排序
    @Test
    public void findBySort(){
        MongoClient mongoClient = new MongoClient( "localhost" , 27017 );
        MongoDatabase db = mongoClient.getDatabase("dbtest"); 
        MongoCollection<Document> collection = db.getCollection("users");
        // select * from user where age>= 70 and age<=100 order by sex desc ,age desc
        FindIterable<Document> sort = collection.find(Filters.and(Filters.lte("age", 100),Filters.gte("age", 70))).sort(Indexes.descending("sex","age")).projection(new Document().append("_id", 0));
        for (Document document : sort) {
            System.out.println(document);
        }
        mongoClient.close();
    }
  • update
    @Test
    public void update(){
        MongoClient mongoClient = new MongoClient( "localhost" , 27017 );
        MongoDatabase db = mongoClient.getDatabase("dbtest"); 
        MongoCollection<Document> collection = db.getCollection("users");
        // udpate users set name = '大神' where name = 'white11'
        UpdateResult updateOne = collection.updateOne(Filters.eq("name", "white11"), new Document().append("$set",new Document("name", "大神")));

        UpdateResult updateMany = collection.updateMany(Filters.lt("age", 10), new Document().append("$inc", new Document().append("age", -100)));
        // 影响行数 
        System.out.println(updateMany.getModifiedCount());

        mongoClient.close();
    }
  • delete
    @Test
    public void delete(){
        MongoClient mongoClient = new MongoClient( "localhost" , 27017 );
        MongoDatabase db = mongoClient.getDatabase("dbtest"); 
        MongoCollection<Document> collection = db.getCollection("users");
        // delete users where name = 'white10'
        collection.deleteOne(Filters.eq("name", "white10"));
        // delete users where age < 10
        collection.deleteMany(Filters.lt("age", 10));
        mongoClient.close();
    }
点击查看更多内容
6人点赞

若觉得本文不错,就分享一下吧!

评论

作者其他优质文章

正在加载中
JAVA开发工程师
手记
粉丝
8549
获赞与收藏
6550

关注作者,订阅最新文章

阅读免费教程

感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦
今天注册有机会得

100积分直接送

付费专栏免费学

大额优惠券免费领

立即参与 放弃机会
意见反馈 帮助中心 APP下载
官方微信

举报

0/150
提交
取消