MongoDB使用聚合框架计算字段为真的次数

时间:2016-08-14 18:19:32

标签: java mongodb count aggregation-framework

概要

尝试计算具有“看到”字段的用户等于'false'

的次数

(邮件)收集示例

{
 to : "jimmy",
 from : "johny",
 message : "Hey",
 seen: false
},
{
 to : "jimmy",
 from : "Maggy",
 message : "Hello",
 seen: true
},
{
 to : "jimmy",
 from : "Sam",
 message : "How are you?",
 seen: false
},
{
 to : "jimmy",
 from : "johny",
 message : "It's me again",
 seen: false
}

具有Mongo聚合的Java方法

  //WHERE 'to' EQUALS 'jimmmy'
  //COUNT 'seen' EQUALS 'false'

我尝试了什么

    public int getTotalUnseen(String toUser){

AggregateIterable<Document> iterable = db.getCollection("mail").aggregate(asList(
        new Document("$match", new Document("to", "jimmy")),
        new Document("$group", new Document("_id", "$seen").append("count", new Document("$sum", 1)))));

    }

期望的结果

int x = getTotalUnseenCount("jimmy");
System.out.println("Result : "+ x);


//Result : 3

1 个答案:

答案 0 :(得分:2)

您可以尝试以下方法:

Query query = new Query();
query.addCriteria(Criteria.where("to").is("jimmy").and("seen").is(true));    
mongoTemplate.count(query, "mail");