引言
最近在用MongoDB 所以总结,方便以后查看,也希望能帮助你。
import org.springframework.data.mongodb.core.MongoTemplate;
@Autowired
MongoTemplate mongoTemplate;
@Override
public List<UserInvoice> findByUserId(long userId) {
Query queue = new Query().addCriteria(Criteria.where("userId").is(userId));
return mongoTemplate.find(queue, UserInvoice.class);
}
// upsert 相同则修改,不同则新增
@Override
public void upsert(Area area) {
mongoTemplate.upsert(new Query().addCriteria(Criteria.where("provinceCode").is(area.getProvinceCode())), new Update()
.set("provinceCode", area.getProvinceCode())
.set("provinceName", area.getProvinceName())
.set("cityCode", area.getCityCode())
.set("cityName", area.getCityName())
.set("countyCode", area.getCountyCode())
.set("countyName", area.getCityName())
.set("townCode", area.getTownCode())
.set("townName", area.getTownName()),
Area.class);
}
@Override
public UserInvoice create(UserInvoice userInvoice) {
mongoTemplate.insert(userInvoice);
if (StringUtils.isEmpty(userInvoice.getId())) {
return null;
}
return userInvoice;
}
@Override
public long update(UserInvoice userInvoice) {
Query query = new Query().addCriteria(Criteria.where("id").is(userInvoice.getId()));
return mongoTemplate.updateFirst(query, new Update().set("phone", userInvoice.getPhone())
.set("address", userInvoice.getAddress())
.set("bankAccount", userInvoice.getBankAccount())
.set("head", userInvoice.getHead())
.set("bankName", userInvoice.getBankName())
.set("taxNo", userInvoice.getTaxNo())
.set("userId", userInvoice.getUserId())
.set("defaultUse", userInvoice.isDefaultUse())
.set("type", userInvoice.getType().toString()),
UserInvoice.class).getModifiedCount();
}
@Override
public long delete(String invoiceId) {
Query query = new Query().addCriteria(Criteria.where("id").is(invoiceId));
return mongoTemplate.remove(query, UserInvoice.class).getDeletedCount();
}
/*
根据name匹配word、根据phone匹配word、并且状态等于active
orOperator -- 或者
*/
@Override
public List<Feedback> find(int page, int limit, String word) {
Criteria criteria = new Criteria();
/*
is精确匹配,模糊匹配 使用regex
*/
criteria.orOperator(Criteria.where("name").regex(word), Criteria.where("phone").regex(word)).and("status").is(Status.active);
// 模糊查询
import java.util.regex.Pattern;
if (StringUtils.isNotEmpty(keyword)) {
Pattern pattern = Pattern.compile("^.*" + keyword + ".*$", Pattern.CASE_INSENSITIVE);
query.addCriteria(Critera.where("target.name").regex(pattern));
}
// 加dto 转换问题
@Document(collection = "xk_user_favorite")
public static final String COLLECTION_NAME = "xk_user_favorite";
mongoTemplate.find(query, XkUserAuthDto.class,XkUserAuth.COLLECTION_NAME);
/*
分页查询:skip("跳过的数据条数").limit("一页的数据条数");
rows 内容多少条,page页数
*/
query.with(new Sort(Sort.Direction.DESC, "updatedAt")).limit(limit).skip((page - 1) * limit);
}
/*
排序:倒序
*/
Query query = new Query().addCriteria(Criteria.where("id").is(id))
query.with(new Sort(Sort.Direction.DESC, "updatedAt")).limit(limit).skip(page * limit);
/**
* 查询所有
*
* @return
*/
@Override
public List<Area> findByAll() {
return mongoTemplate.findAll(Area.class);
}
/*
mongodb在使用 内部类(文档嵌套文档),内部类也要加 @Document 请用以下方法,不能用push(已有的数组末尾加入一个元素,要是元素不存在,就会创建一个新的元素)
*/
Set<Categoy.Child> children = Optional.ofNullable(oldCategory.getChildren()).orElse(new HashSet<>());
children.addAll(childList);
mongoTemplate.updateFirst(new Query().addCriteria(Criteria.where("code").is(parentCode)), new Update().set("children",children), Category.class);
//save :有则改之,无则加之
/*
$ne :表示不等于;不存在,一个值不在数组里时就把它加进去,避免重复数据
$gte : 大于等于
Criteria nin (Object… o) $nin 不包含
一个Criteria中只能有一个andOperator,and可以多个,我们查询并列条件时,比较建议使用and方法。
*/
//完全匹配
Pattern pattern = Pattern.compile("^王$", Pattern.CASE_INSENSITIVE);
//右匹配
Pattern pattern = Pattern.compile("^.*王$", Pattern.CASE_INSENSITIVE);
//左匹配
Pattern pattern = Pattern.compile("^王.*$", Pattern.CASE_INSENSITIVE);
//模糊匹配
Pattern pattern = Pattern.compile("^.*王.*$", Pattern.CASE_INSENSITIVE);
Query query = Query.query(Criteria.where(fieldName).regex(pattern));
List<SimpleUserInfo> users = mongoTemplate.find(query, SimpleUserInfo.class, classname);
return users;
// 默认情况下,insert并不检查文档是否插入过了,所以,为了避免插入的文档中包含与唯一键重复的值,可能要用安全插入才能满足要求, 这样,在插入这样的文档时会看到存在重复键错误的提示。
try {
mongoTemplate.insert(mSeat);
} catch (Exception e) {
if (e instanceof DuplicateKeyException) {
throw new UserException(UserException.Codes.MONGODB_ID_ISEXIST);
}
throw e;
}
//创建唯一索引,并消除重复数据。
db.test.ensureIndex({"userid":1},{"unique":true,"dropDups":true})
//我们可以创建复合唯一索引,即保证复合键值唯一即可。如:
db.test.ensureIndex({"userid":1,"age":1},{"unique":true})