| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970 |
- package com.zswl.dataservice.service.base;
- import com.mongodb.client.result.UpdateResult;
- import com.zswl.dataservice.utils.CommonUtil;
- import lombok.extern.slf4j.Slf4j;
- import org.apache.commons.lang3.StringUtils;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.data.mongodb.core.MongoTemplate;
- import org.springframework.data.mongodb.core.query.Criteria;
- import org.springframework.data.mongodb.core.query.Query;
- import org.springframework.data.mongodb.core.query.Update;
- import org.springframework.stereotype.Service;
- import java.util.Map;
- /**
- * @author TRX
- * @date 2024/5/31
- */
- @Slf4j
- @Service
- public class CommonService {
- @Autowired
- private MongoTemplate mongoTemplate;
- /**
- * 编辑数据
- *
- * @param standardData
- * @param collectionName
- * @return
- */
- public Object updateData(Map<String, Object> standardData, String collectionName) {
- collectionName = CommonUtil.getCollectionName(collectionName);
- Object id = standardData.get("id");
- if (id != null) {
- Query query = new Query(Criteria.where("_id").is(id));
- Update update = new Update();
- standardData.forEach((key, value) -> {
- if (!"id".equals(key)) {
- update.set(key, value);
- }
- });
- UpdateResult updateResult = mongoTemplate.updateMulti(query, update, collectionName);
- return updateResult.getUpsertedId();
- }
- return null;
- }
- public Object updateData(Map<String, Object> where, Map<String, Object> standardData, String collectionName) {
- collectionName = CommonUtil.getCollectionName(collectionName);
- Criteria criteria = new Criteria();
- if (where != null) {
- where.forEach((key, value) -> {
- criteria.and(key).is(value);
- });
- }
- Query query = new Query(criteria);
- Update update = new Update();
- standardData.forEach((key, value) -> {
- if (!"id".equals(key)) {
- update.set(key, value);
- }
- });
- UpdateResult updateResult = mongoTemplate.updateMulti(query, update, collectionName);
- return updateResult.getUpsertedId();
- }
- }
|