java 操作Mongodb

CRUD基础操作

Springboot 操作 MongoDB 有两种方式。

  • 第一种方式是采用 Springboot 官方推荐的 JPA 方式,这种操作方式,使用简单但是灵活性比较差。
  • 第二种方式是采用 Spring Data MongoDB 封装的 MongoDB 官方 Java 驱动 MongoTemplate 对 MongoDB 进行操作,这种方式非常灵活,能满足绝大部分需求。

本文将采用第二种方式进行介绍!

插入文档

MongoTemplate提供了insert()方法,用于插入文档,示例代码如下:

  • 用于插入文档

没指定集合名称时,会取@Document注解中的集合名称

@RunWith(SpringRunner.class)
@SpringBootTest
public class PersonServiceTest {
   

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 插入文档
     * @throws Exception
     */
    @Test
    public void insert() throws Exception {
   
        Person person =new Person();
        person.setId(1l);
        person.setUserName("张三");
        person.setPassWord("123456");
        person.setCreateTime(new Date());
        mongoTemplate.insert(person);
    }
}

  • 自定义集合名称,插入文档
@RunWith(SpringRunner.class)
@SpringBootTest
public class PersonServiceTest {
   

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 自定义集合,插入文档
     * @throws Exception
     */
    @Test
    public void insertCustomCollection() throws Exception {
   
        Person person =new Person();
        person.setId(1l);
        person.setUserName("张三");
        person.setPassWord("123456");
        person.setCreateTime(new Date());
        mongoTemplate.insert(person, "custom_person");
    }
}

  • 自定义集合,批量插入文档

如果采用批量插入文档,必须指定集合名称

@RunWith(SpringRunner.class)
@SpringBootTest
public class PersonServiceTest {
   

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 自定义集合,批量插入文档
     * @throws Exception
     */
    @Test
    public void insertBatch() throws Exception {
   
        List<Person> personList = new ArrayList<>();
        Person person1 =new Person();
        person1.setId(10l);
        person1.setUserName("张三");
        person1.setPassWord("123456");
        person1.setCreateTime(new Date());
        personList.add(person1);

        Person person2 =new Person();
        person2.setId(11l);
        person2.setUserName("李四");
        person2.setPassWord("123456");
        person2.setCreateTime(new Date());
        personList.add(person2);

        mongoTemplate.insert(personList, "custom_person");
    }
}

存储文档

MongoTemplate提供了save()方法,用于存储文档。

在存储文档的时候会通过主键ID进行判断,如果存在就更新,否则就插入,示例代码如下:

  • 存储文档,如果没有插入,否则通过主键ID更新
@RunWith(SpringRunner.class)
@SpringBootTest
public class PersonServiceTest {
   

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 存储文档,如果没有插入,否则更新
     * @throws Exception
     */
    @Test
    public void save() throws Exception {
   
        Person person =new Person();
        person.setId(13l);
        person.setUserName("八八");
        person.setPassWord("123456");
        person.setAge(40);
        person.setCreateTime(new Date());
        mongoTemplate.save(person);
    }
}

  • 自定义集合,存储文档
@RunWith(SpringRunner.class)
@SpringBootTest
public class PersonServiceTest {
   

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 自定义集合,存储文档
     * @throws Exception
     */
    @Test
    public void saveCustomCollection() throws Exception {
   
        Person person =new Person();
        person.setId(1l);
        person.setUserName("张三");
        person.setPassWord("123456");
        person.setCreateTime(new Date());
        mongoTemplate.save(person, "custom_person");
    }
}

更新文档

MongoTemplate提供了updateFirst()和updateMulti()方法,用于更新文档,示例代码如下:

  • 更新文档,匹配查询到的文档数据中的第一条数据
@RunWith(SpringRunner.class)
@SpringBootTest
public class PersonServiceTest {
   

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 更新文档,匹配查询到的文档数据中的第一条数据
     * @throws Exception
     */
    @Test
    public void updateFirst() throws Exception {
   
        //更新对象
        Person person =new Person();
        person.setId(1l);
        person.setUserName("张三123");
        person.setPassWord("123456");
        person.setCreateTime(new Date());

        //更新条件
        Query query= new Query(Criteria.where("id").is(person.getId()));

        //更新值
        Update update= new Update().set("userName", person.getUserName()).set("passWord", person.getPassWord());
        //更新查询满足条件的文档数据(第一条)
        UpdateResult result =mongoTemplate.updateFirst(query,update, Person.class);
        if(result!=null){
   
            System.out.println("更新条数:" + result.getMatchedCount());
        }
    }
}

  • 更新文档,匹配查询到的文档数据中的所有数据
@RunWith(SpringRunner.class)
@SpringBootTest
public class PersonServiceTest {
   

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 更新文档,匹配查询到的文档数据中的所有数据
     * @throws Exception
     */
    @Test
    public void updateMany() throws Exception {
   
        //更新对象
        Person person =new Person();
        person.setId(1l);
        person.setUserName("张三");
        person.setPassWord("123456");
        person.setCreateTime(new Date());

        //更新条件
        Query query= new Query(Criteria.where("id").is(person.getId()));

        //更新值
        Update update= new Update().set("userName", person.getUserName()).set("passWord", person.getPassWord());
        //更新查询满足条件的文档数据(全部)
        UpdateResult result = mongoTemplate.updateMulti(query, update, Person.class);
        if(result!=null){
   
            System.out.println("更新条数:" + result.getMatchedCount());
        }
    }
}

删除文档

MongoTemplate提供了remove()、findAndRemove()和findAllAndRemove()方法,用于删除文档,示例代码如下:

  • 删除符合条件的所有文档
@RunWith(SpringRunner.class)
@SpringBootTest
public class PersonServiceTest {
   

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 删除符合条件的所有文档
     * @throws Exception
     */
    @Test
    public void remove() throws Exception {
   
        Person person =new Person();
        person.setId(1l);
        person.setUserName("张三");
        person.setPassWord("123456");
        person.setCreateTime(new Date());

        Query query = new Query(Criteria.where("userName").is(person.getUserName()));
        DeleteResult result = mongoTemplate.remove(query, Person.class);
        System.out.println("删除条数:" + result.getDeletedCount());
    }
}

  • 删除符合条件的单个文档,并返回删除的文档
@RunWith(SpringRunner.class)
@SpringBootTest
public class PersonServiceTest {
   

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 删除符合条件的单个文档,并返回删除的文档
     * @throws Exception
     */
    @Test
    public void findAndRemove() throws Exception {
   
        Person person =new Person();
        person.setId(1l);
        person.setUserName("张三");
        person.setPassWord("123456");
        person.setCreateTime(new Date());

        Query query = new Query(Criteria.where("id").is(person.getId()));
        Person result = mongoTemplate.findAndRemove(query, Person.class);
        System.out.println("删除的文档数据:" + result.toString());
    }
}

  • 删除符合条件的所有文档,并返回删除的文档
@RunWith(SpringRunner.class)
@SpringBootTest
public class PersonServiceTest {
   

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 删除符合条件的所有文档,并返回删除的文档
     * @throws Exception
     */
    @Test
    public void findAllAndRemove() throws Exception {
   
        Person person =new Person();
        person.setId(1l);
        person.setUserName("张三");
        person.setPassWord("123456");
        person.setCreateTime(new Date());

        Query query = new Query(Criteria.where("id").is(person.getId()));
        List<Person> result = mongoTemplate.findAllAndRemove(query, Person.class);
        System.out.println("删除的文档数据:" + result.toString());
    }
}

查询文档

MongoTemplate提供了非常多的文档查询方法,日常开发中用的最多的就是find()方法,示例代码如下:

  • 查询集合中的全部文档数据
@RunWith(SpringRunner.class)
@SpringBootTest
public class PersonServiceTest {
   

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 查询集合中的全部文档数据
     * @throws Exception
     */
    @Test
    public void findAll() throws Exception {
   
        List<Person> result = mongoTemplate.findAll(Person.class);
        System.out.println("查询结果:" + result.toString());
    }
}

查询集合中指定的ID文档数据

@RunWith(SpringRunner.class)
@SpringBootTest
public class PersonServiceTest {
   

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 查询集合中指定的ID文档数据
     * @throws Exception
     */
    @Test
    public void findById() {
   
        long id = 1l;
        Person result = mongoTemplate.findById(id, Person.class);
        System.out.println("查询结果:" + result.toString());
    }
}

根据条件查询集合中符合条件的文档,返回第一条数据

@RunWith(SpringRunner.class)
@SpringBootTest
public class PersonServiceTest {
   

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 根据条件查询集合中符合条件的文档,返回第一条数据
     */
    @Test
    public void findOne() {
   
        String userName = "张三";
        Query query = new Query(Criteria.where("userName").is(userName));
        Person result = mongoTemplate.findOne(query, Person.class);
        System.out.println("查询结果:" + result.toString());
    }
}

根据条件查询集合中符合条件的文档

@RunWith(SpringRunner.class)
@SpringBootTest
public class PersonServiceTest {
   

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 根据条件查询集合中符合条件的文档
     */
    @Test
    public void findByCondition() {
   
        String userName = "张三";
        Query query = new Query(Criteria.where("userName").is(userName));
        List<Person> result 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值