springboot整和mogodb(MongoRepository)简单操作(增删改查,模糊、条件和分页查询)和SpringData 方法定义规范

Spring Data提供了对mongodb数据访问的支持,我们只需要继承MongoRepository类

前面的基础流程应用依赖,创建实体类参考下这篇文章参考文本

1.创建接口继承MongoRepository

package com.example.mongodb.repository;

import com.example.mongodb.entity.Student;
import org.springframework.data.mongodb.repository.MongoRepository;

public interface StudentRespostiory extends MongoRepository <Student,String>{
}

然后我们在测试类中注入StudentRepository调用 MongoRepository类封装好的方法

2.添加记录方法

  @Test
    public void create(){
         Student student=new Student();
         student.setName("mary");
         student.setEmail("mary@168.com");
         student.setAge(17);
         Object s1 = studentRespostiory.save(student);
         System.out.println("保存的对象:"+s1);
     }

通过.save()将依据创建好的对象存入数据库

我们在linux下查询

成功的添加了数据

3.查询所有数据

     @Test
    public void  findList(){
         List<Student> studentList = studentRespostiory.findAll();
         for (Student s:studentList) {
             System.out.println("查询记录:"+s);
         }
     }

 结果

 4.根据id查询

    @Test
    public void  findById(){
        Student student = studentRespostiory.findById("62049665dd5a9245cc968271").get();
        System.out.println("根据id查询"+student);
    }

 5.添加查询

    @Test
    public void findStudentList(){
        Student student = new Student();
        student.setAge(16);
        student.setName("jock");
        Example<Student> stExample= Example.of(student);
        List<Student> userList = studentRespostiory.findAll(stExample);
        System.out.println(userList);
    }

 通过findAll查询数据记录但是我们要把封装好的条件对象stExample传入到这个方法中,先把封装好的对象用Example.of()处理

 6.模糊查询

    @Test
    public void findStudentList(){
         //固定格式--模糊匹配规则
        ExampleMatcher matcher=ExampleMatcher.matching()
                .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING)
                .withIgnoreCase(true);
        
        Student student = new Student();
        student.setName("c");
        Example<Student> stExample = Example.of(student,matcher);
        List<Student> studentList = studentRespostiory.findAll(stExample);
        for (Student s:studentList) {
            System.out.println("查询记录:"+s);
        }
    }

和条件查询差不多只要传入模糊查询的匹配规则。

7.分页查询

条件带分页

    @Test
    public void findPage(){
        Pageable pageable= PageRequest.of(0,3);
        Student student=new Student();
        student.setName("mary");

        Example<Student> stExample = Example.of(student);
        Page<Student> all = studentRespostiory.findAll(stExample, pageable);
        System.out.println(all);

    }

我们调用PageRequest.of(0,3)设置当前页是第一页 并且每一页记录数为3然后返回给pageable对象 在做查询的时候把这个pageable对象传入到查询方法中

结果

 8.更新数据

    @Test
    public void updata(){
        Student student = studentRespostiory.findById("62049665dd5a9245cc968271").get();
        student.setName("DFP77");
        studentRespostiory.save(student);
    }

和插入数据方法一样但是这里如果有识别带有id值会根据id修改之前的值

查看数据库

9.删除 

    @Test
    public void del(){
         studentRespostiory.deleteById("62049665dd5a9245cc968271");
    }

调用方法传入id

10.定义规范

Spring Data提供了对mongodb数据访问的支持,我们只需要继承MongoRepository类,按照Spring Data规范就可以了

SpringData 方法定义规范

1、不是随便声明的,而需要符合一定的规范
2、 查询方法以find | read | get开头
3、 涉及条件查询时,条件的属性用条件关键字连接
4、 要注意的是:条件属性首字母需要大写
5、 支持属性的级联查询,但若当前类有符合条件的属性则优先使用,而不使用级联属性,若需要使用级联属性,则属性之间使用_强制进行连接

这样我们在接口写的方法不需要我们自己实现,MongoRepository根据定义的规则自己帮我们实现方法。

  • 4
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 好的,以下是一个使用 Python 连接 MongoDB 数据库进行增删改查的类的示例代码: ```python import pymongo class MongoDB: def __init__(self, host, port, database): self.client = pymongo.MongoClient(host, port) self.db = self.client[database] def insert_one(self, collection, document): """插入一条记录""" self.db[collection].insert_one(document) def insert_many(self, collection, documents): """插入多条记录""" self.db[collection].insert_many(documents) def find_one(self, collection, query): """查询一条记录""" return self.db[collection].find_one(query) def find(self, collection, query, page_size=10, page_num=1): """分页查询多条记录""" skip = (page_num - 1) * page_size return self.db[collection].find(query).skip(skip).limit(page_size) def update_one(self, collection, query, update): """更新一条记录""" self.db[collection].update_one(query, update) def update_many(self, collection, query, update): """更新多条记录""" self.db[collection].update_many(query, update) def delete_one(self, collection, query): """删除一条记录""" self.db[collection].delete_one(query) def delete_many(self, collection, query): """删除多条记录""" self.db[collection].delete_many(query) ``` 以下是使用这个类的示例: ```python # 实例化类 mongodb = MongoDB('localhost', 27017, 'test') # 插入一条记录 mongodb.insert_one('users', {'name': 'Alice', 'age': 20}) # 插入多条记录 mongodb.insert_many('users', [{'name': 'Bob', 'age': 21}, {'name': 'Charlie', 'age': 22}]) # 查询一条记录 print(mongodb.find_one('users', {'name': 'Alice'})) # 分页查询多条记录 ### 回答2: 下面是一个用 Python 写的类,可以进行 MONGO 数据库的增删改查,并包含分页查询的示例代码: ```python from pymongo import MongoClient class MongoHandler: def __init__(self, host='localhost', port=27017): self.client = MongoClient(host, port) self.db = self.client['mydatabase'] self.collection = self.db['mycollection'] def insert(self, data): result = self.collection.insert_one(data) return result.inserted_id def find(self, query): results = self.collection.find(query) return [result for result in results] def update(self, filter_query, update_query): result = self.collection.update_many(filter_query, update_query) return result.modified_count def delete(self, query): result = self.collection.delete_many(query) return result.deleted_count def find_with_pagination(self, query, page_size, page_number): skip_count = page_size * (page_number - 1) results = self.collection.find(query).skip(skip_count).limit(page_size) return [result for result in results] # 示例代码 if __name__ == '__main__': mongo_handler = MongoHandler() # 插入数据 data = { 'name': 'John', 'age': 25, 'country': 'USA' } inserted_id = mongo_handler.insert(data) print(f'Inserted ID: {inserted_id}') # 查询数据 query = {'age': {'$gte': 20}} results = mongo_handler.find(query) for result in results: print(result) # 更新数据 filter_query = {'country': 'USA'} update_query = {'$set': {'age': 30}} modified_count = mongo_handler.update(filter_query, update_query) print(f'Modified count: {modified_count}') # 删除数据 delete_query = {'age': {'$lt': 30}} deleted_count = mongo_handler.delete(delete_query) print(f'Deleted count: {deleted_count}') # 分页查询数据 query = {} page_size = 2 page_number = 2 results = mongo_handler.find_with_pagination(query, page_size, page_number) for result in results: print(result) ``` 这段代码定义了一个 `MongoHandler` 类,初始化时连接到本地的 MongoDB 数据库,并操作 `mydatabase` 数据库中的 `mycollection` 集合。类中的 `insert` 方法用于插入数据,`find` 方法用于查询数据,`update` 方法用于更新数据,`delete` 方法用于删除数据。另外还定义了一个 `find_with_pagination` 方法,用于分页查询数据。 在示例代码中,首先使用 `insert` 方法插入了一条数据,然后使用 `find` 方法查询了年龄大于等于 20 的数据,使用 `update` 方法将所有国家为 USA 的数据的年龄更新为 30,使用 `delete` 方法删除了年龄小于 30 的数据。最后使用 `find_with_pagination` 方法进行了分页查询,每页显示 2 条数据,查找第 2 页的数据。以上操作均打印出了相应的结果。 ### 回答3: 下面是一个用Python写的可以进行Mongo数据库增删改查的类,包含分页查询的示例代码: ```python from pymongo import MongoClient class MongoDB: def __init__(self, db_name, collection_name): self.client = MongoClient() self.db = self.client[db_name] self.collection = self.db[collection_name] def insert(self, data): self.collection.insert_one(data) def delete(self, query): self.collection.delete_many(query) def update(self, query, update_data): self.collection.update_many(query, {"$set": update_data}) def find(self, query, projection=None, limit=None, skip=None): cursor = self.collection.find(query, projection) if limit: cursor = cursor.limit(limit) if skip: cursor = cursor.skip(skip) results = [] for doc in cursor: results.append(doc) return results # 示例代码 # 创建MongoDB类的实例 mongo = MongoDB("test_database", "test_collection") # 插入数据 data1 = {"name": "Alice", "age": 25} mongo.insert(data1) data2 = {"name": "Bob", "age": 27} mongo.insert(data2) data3 = {"name": "Charlie", "age": 30} mongo.insert(data3) # 查询所有数据 all_data = mongo.find({}) for data in all_data: print(data) # 查询年龄大于等于26的数据,只返回name字段 query = {"age": {"$gte": 26}} projection = {"name": 1, "_id": 0} data_with_condition = mongo.find(query, projection) for data in data_with_condition: print(data) # 删除年龄大于等于26的数据 mongo.delete(query) # 更新年龄小于30的数据,将age字段加1 update_query = {"age": {"$lt": 30}} update_data = {"age": {"$inc": 1}} mongo.update(update_query, update_data) ``` 上述代码示例了如何使用MongoDB类进行增删改查操作。更具体的使用方式和参数说明可以参考PyMongo的官方文档:https://pymongo.readthedocs.io/

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值