使用springboot mongodb工具,删除多余字段。
1、pom文件依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
2、代码实现
topping、toppingTime是需要删除的字段。
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
...
import org.springframework.data.domain.Sort;
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 javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;
public ResponseBean noTopping(ThreadCommentVo threadCommentVo) {
String source = threadCommentVo.getSource();
String commentId = threadCommentVo.getCommentId();
Query query = new Query(Criteria.where("commentId").is(commentId));
ThreadCommentEntity threadCommentEntity = (ThreadCommentEntity) mongoUtils.getOneByCondition(query, ThreadCommentEntity.class, getCollection(source));
System.out.println("threadCommentEntity = " + threadCommentEntity);
if (threadCommentEntity == null || threadCommentEntity.getTopping() == null || threadCommentEntity.getTopping() != 1) {
return ResponseBean.builder().code(-1).msg("failed").data("非置顶帖子").build();
}
Update update = new Update();
// 删除topping、toppingTime字段
update.unset("topping");
update.unset("toppingTime");
boolean ret = mongoUtils.update(query, update, ThreadCommentEntity.class, getCollection(source));
return ResponseBean.builder().code(100).msg("success").data(ret).build();
}