MongoDB简单使用,Java对象与表对应操作

MongoDB简单使用

1.基本增删改查

1.1提前准备

1.11 导入pom
<!--        mongo driver-->
        <dependency>
            <groupId>org.mongodb</groupId>
            <artifactId>mongo-java-driver</artifactId>
            <version>3.6.4</version>
        </dependency>
<!--        junit-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>


        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.26</version>
        </dependency>
1.12 连接工具类 MongoDBUtil
public class MongoDBUtil {



    /**
     * 连接到数据库
     * @param databaseName 数据库名字
     * @return connect
     */
    public static MongoDatabase getConnect(String databaseName){

        //连接到 mongodb 服务
        MongoClient mongoClient = new MongoClient("localhost", 27017);
        //连接到数据库
        MongoDatabase mongoDatabase  = mongoClient.getDatabase(databaseName);
        //返回连接数据库对象
        return mongoDatabase;
    }


    /**
     *  获取表对象
     * @param databaseName 数据库名字
     * @param table 表名字
     * @return
     */
    public static  MongoCollection<Document> getTable (String databaseName,String table){

        //连接到 mongodb 服务
        MongoClient mongoClient = new MongoClient("localhost", 27017);
        //连接到数据库
        MongoDatabase mongoDatabase  = mongoClient.getDatabase(databaseName);

        //获取表对象
        MongoCollection<Document> collection = mongoDatabase.getCollection(table);
        return collection;
    }


    /**
     * 创建编解码注册器,用来处理 pojo和bson之间的相互转换
     * @return CodecRegistry
     */
    public static CodecRegistry codecRegistry(){
        return CodecRegistries.fromRegistries(MongoClient.getDefaultCodecRegistry(),
                CodecRegistries.fromProviders(PojoCodecProvider.builder().automatic(true).build()));
    }


    public static void close(MongoClient client){
        client.close();
    }

}
1.13 实体类
@Data
public class ProjectEntity  {

    @Override
    public String toString() {
        return "ProjectEntity{" +
                "name='" + name + '\'' +
                '}';
    }

    /**
     * 工程名
     */
    @Field
    private String name;

    public ProjectEntity() {
    }

    public ProjectEntity(String name) {

        this.name = name;
    }

1.2 简单增删改查

 //创建集合   相当于表名
    MongoCollection<Document> collection =MongoDBUtil.getTable("test","project");

1.2.1 增加
/**
     * 添加test
     * 创建document对象
     *
     * 插入一个文档,使用 MongoCollection 对象的 insertOne() 方法,
     * 该方法接收一个 Document 对象作为要插入的数据
     */
    @Test
    public void test1(){

        //创建document对象,进行增加操作
        Document document = new Document();
        document.append("name","张三")
                .append("age","18")
                .append("sex","男");

        Map<String,Object> map = new HashMap<>();

        collection.insertOne(document);
    }
1.2.2修改
 /**
     * 修改测试
     *  修改单个文档,使用 MongoCollection 对象的 updateOne() 方法,
     *  该方法接收两个参数,第一个数据类型为 Bson 的过滤器筛选出需要修改的文档,
     *  第二个参数数据类型为 Bson 指定如何修改筛选出的文档。然后修改过滤器筛选出的第一个文档
     *
     */
    @Test
    public void test2(){

        //过滤器
        Bson bson = Filters.eq("name", "张三");
        //指定修改的更新文档
        Document document = new Document("$set", new Document("age", 15));
        //修改
        UpdateResult result = collection.updateOne(bson, document);
        System.out.println(result);


    }
1.2.3查询
 /**
     * 查询
     * 使用 MongoCollection 对象的 find() 方法,
     * 该方法有多个重载方法,可以使用不带参数的 find() 方法查询集合中的所有文档,
     * 也可以通过传递一个 Bson 类型的 过滤器查询符合条件的文档。
     * 这几个重载方法均返回一个 FindIterable 类型的对象,可通过该对象遍历出查询到的所有文档。
     *  Filters.eq()   //匹配到等于指定值的数据
     *  Filters.gt()   //匹配到大于指定值的数据
     *  Filters.gte()   //匹配到大于等于定值的数据
     *  Filters.lt()   //匹配到小于指定值的数据
     *
        Filters.regex() 模糊查询

     FindIterable<Document> b=collection.find().skip(0).limit(3);//跳过第0条数据,一次看三条数据
     *
     *  Bson b=new Document("id",-1);//根据id倒叙排序   1 升序  -1降序
     * FindIterable<Document> d=collection.find().sort(b);
     */
    @Test
    public void test3(){
        //find()查询所有
//        FindIterable<Document> findIterable = collection.find();

        //过滤器
        Bson bson = Filters.gt("age",15);
        //带条件查询
        FindIterable<Document> documents = collection.find(bson).skip(0).limit(3).sort(new Document("age",-1));

        //获取游标
        MongoCursor<Document> cursor = documents.iterator();
        while (cursor.hasNext()){
            System.out.println("---"+cursor);
            System.out.println(cursor.next());
        }
    }
1.2.4删除
    /**
     * 删除测试

     */

    @Test
    public void test4(){
//        DeleteResult id = collection.deleteOne(Filters.eq("age",100));
//        System.out.println(id);
    }

1.3 进阶版: java实体类 与表对应的增删改查


    //获取连接 数据库
    MongoDatabase connect = MongoDBUtil.getConnect("weekly");
    //创建集合   相当于表名
    MongoCollection<Weekly> collection = connect.getCollection("weekly", Weekly.class).withCodecRegistry(MongoDBUtil.codecRegistry());
1.3.1增加、查询
collection.insertOne(new ProjectEntity("工程4"));
collection.insertMany(Arrays.asList(new ProjectEntity("工程1"),new ProjectEntity("工程2")));
FindIterable<ProjectEntity> projectEntities = collection.find();
 MongoCursor<ProjectEntity> iterator = projectEntities.iterator();
//        ProjectEntity first = projectEntities.first();
        FindIterable<ProjectEntity> limit = projectEntities.skip(0).limit(5);
//        System.out.println(limit);
        while (iterator.hasNext()){
            System.out.println(iterator.next());
        }

其他调用方法都一样不再演示!!可以看上面简单的CRUD,方法都一样

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值