java mongodb分组查询并求count
时间: 2024-01-02 15:21:57 浏览: 88
以下是使用Java和MongoDB进行分组查询并求count的示例代码:
```java
import com.mongodb.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;
import java.util.Arrays;
public class GroupCountExample {
public static void main(String[] args) {
// 连接到MongoDB数据库
MongoClient mongoClient = new MongoClient("localhost", 27017);
MongoDatabase database = mongoClient.getDatabase("your_database_name");
MongoCollection<Document> collection = database.getCollection("your_collection_name");
// 构建分组查询条件
Document groupFields = new Document("_id", "$c_sender");
groupFields.put("count", new Document("$sum", 1));
// 执行分组查询
Document group = new Document("$group", groupFields);
Iterable<Document> results = collection.aggregate(Arrays.asList(group));
// 输出结果
for (Document result : results) {
String sender = result.getString("_id");
int count = result.getInteger("count");
System.out.println("Sender: " + sender + ", Count: " + count);
}
// 关闭连接
mongoClient.close();
}
}
```
请注意,你需要将代码中的`your_database_name`和`your_collection_name`替换为你实际使用的数据库和集合名称。
阅读全文