1. 程式人生 > >Springboot MongoDB-MongoTemplate使用筆記

Springboot MongoDB-MongoTemplate使用筆記

分頁、排序

import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import java.util.List;

@ApiModel(description = "分頁實體")
@Data
public class Page<T> {

    @ApiModelProperty(value = "總頁數")
    private Long totalPage;

    @ApiModelProperty
(value = "總記錄數") private Long totalCount; @ApiModelProperty(value = "資料") private List<T> data; @ApiModelProperty(value = "當前頁數") private Long currentPage; }

        Query query = new Query();
        Criteria criteria = new Criteria();
        if ("" != prizeName) {
criteria.and("prizeName").is(prizeName); } if ("" != prizeCode) { criteria.and("prizeCode").is(prizeCode); } query.addCriteria(criteria); //query.with(new Sort(Sort.Direction.ASC, "name")); //按name進行 升序 //預設顯示10頁 query.skip((currentPage -
1) * 10).limit(10); List<ActivityPrize> activityPrizeList = mongoTemplate.find(query, ActivityPrize.class); //long count = mongoTemplate.count(query, Account.class); long count = activityPrizeList.size(); /** * 封裝分頁返回資料 */ Page<ActivityPrize> page = new Page<>(); page.setData(activityPrizeList); page.setTotalCount(count); page.setTotalPage(count % pageSize == 0 ? count / pageSize : count / pageSize + 1); page.setCurrentPage(Long.valueOf(pageSize));

當沒有任何條件時,查出所以文件資料

批量

 @Test
    public void testAccount() {
        BulkOperations ops = mongoTemplate.bulkOps(BulkOperations.BulkMode.UNORDERED, Account.class);
        List<Account> list = new ArrayList<>();
        for (int i = 0; i < 50; i++) {
            Account account = new Account();
            account.setUserName("admin" + i);
            account.setPassWord("password");
            list.add(account);
        }
        ops.insert(list);
        ops.execute();

    }

文件巢狀物件

public class Account{
	...
 	private Set<Role> roles = new HashSet<>();
}
@Test
    public void test9() {
        Query query = new Query();
        Criteria criteria = new Criteria();
        criteria.and("_id").is("364FF769E55A419D8A0F3712C84291AF").and("roles.name").is("admin");
        query.addCriteria(criteria);
        log.debug("result:{}", mongoTemplate.find(query, Account.class));

        //Update update =  Update.update("roles.$.name","admin1");//修改匹配的第一個
        Update update = Update.update("roles.$[].name", "admin1");//修改匹配的所有

        UpdateResult result = mongoTemplate.updateMulti(query, update, Account.class);
        log.debug("UpdateResult:{}", result1);
    }