|
|
@@ -0,0 +1,59 @@
|
|
|
+package cn.reghao.autodop.dmaster.sys.db;
|
|
|
+
|
|
|
+import com.mongodb.BasicDBObject;
|
|
|
+import com.mongodb.client.AggregateIterable;
|
|
|
+import org.bson.Document;
|
|
|
+import org.bson.types.ObjectId;
|
|
|
+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.stereotype.Component;
|
|
|
+
|
|
|
+import java.util.ArrayList;
|
|
|
+import java.util.List;
|
|
|
+
|
|
|
+/**
|
|
|
+ * @author reghao
|
|
|
+ * @date 2021-06-17 15:12:02
|
|
|
+ */
|
|
|
+@Component
|
|
|
+public class MongoQuery {
|
|
|
+ private MongoTemplate mongoTemplate;
|
|
|
+
|
|
|
+ public MongoQuery(MongoTemplate mongoTemplate) {
|
|
|
+ this.mongoTemplate = mongoTemplate;
|
|
|
+ }
|
|
|
+
|
|
|
+ public void aggregate(String col) {
|
|
|
+ String groupById = "$answerId";
|
|
|
+ Document groupObject = new Document("_id", groupById);
|
|
|
+ groupObject.put("total", new BasicDBObject("$sum", 1));
|
|
|
+ groupObject.put("data", new BasicDBObject("$push", "$$ROOT"));
|
|
|
+ Document queryGroup = new Document("$group", groupObject);
|
|
|
+
|
|
|
+ Document sortObject = new Document("$sort", new BasicDBObject("total", -1));
|
|
|
+ Document limitObject = new Document("$limit", 10000);
|
|
|
+
|
|
|
+ List<Document> pipeline = new ArrayList<>();
|
|
|
+ pipeline.add(queryGroup);
|
|
|
+ pipeline.add(sortObject);
|
|
|
+ pipeline.add(limitObject);
|
|
|
+
|
|
|
+ AggregateIterable<Document> result = mongoTemplate.getCollection(col).aggregate(pipeline).allowDiskUse(true);
|
|
|
+ for (Document document : result) {
|
|
|
+ List<Document> list = document.getList("data", Document.class);
|
|
|
+ int size = list.size();
|
|
|
+ // 删除重复的数据
|
|
|
+ if (size > 1) {
|
|
|
+ for (int i = 1; i < size; i++) {
|
|
|
+ Document doc = list.get(i);
|
|
|
+ ObjectId objectId = doc.get("_id", ObjectId.class);
|
|
|
+
|
|
|
+ Query query = new Query();
|
|
|
+ query.addCriteria(Criteria.where("_id").is(objectId));
|
|
|
+ //mongoTemplate.remove(query, col);
|
|
|
+ }
|
|
|
+ }
|
|
|
+ }
|
|
|
+ }
|
|
|
+}
|