Browse Source

优化工具类

johnclot69 3 months ago
parent
commit
1f9ada5203

+ 12 - 11
incubator-game/src/main/java/com/incubator/game/data/mongo/MongoUtil.java

@@ -20,6 +20,7 @@ import java.util.ArrayList;
 import java.util.List;
 import java.util.Map;
 import java.util.Objects;
+import java.util.function.Consumer;
 
 public class MongoUtil {
 
@@ -80,7 +81,7 @@ public class MongoUtil {
 	}
 	
 	public boolean insertMany(String collectionName, List<Document> doc) {
-		if (doc != null && doc.size() > 0) {
+		if (doc != null && !doc.isEmpty()) {
 			mongoClient.getDatabase(DBNAME).getCollection(collectionName).insertMany(doc);
 			return true;
 		}		
@@ -96,15 +97,15 @@ public class MongoUtil {
 	}
 
 	public List<Document> find(String collectionName, Bson filter) {
-		List<Document> resultList = new ArrayList<Document>();
-		if (filter != null) {
-			FindIterable<Document> docs = mongoClient.getDatabase(DBNAME).getCollection(collectionName).find(filter);
-			docs.forEach(new Block<Document>() {
-				public void apply(Document document) {
-					resultList.add(document);
-				}
-			});
-		}
+		List<Document> resultList = new ArrayList<>();
+		// 获取数据库和集合
+		MongoCollection<Document> collection = mongoClient.getDatabase(DBNAME).getCollection(collectionName);
+		// 如果过滤器为空,使用默认过滤器
+		filter = (filter != null) ? filter : new Document();
+		// 查询集合并收集结果
+		FindIterable<Document> docs = collection.find(filter);
+		docs.forEach((Consumer<Document>) resultList::add);
+
 		return resultList;
 	}
 
@@ -123,7 +124,7 @@ public class MongoUtil {
 	}
 
 	public long getCount(String collectionName) {
-		return getDatabase().getCollection(collectionName).count();
+		return getDatabase().getCollection(collectionName).countDocuments();
 	}
 
 	/**