简体   繁体   English

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

[英]MongoDB count number of times where a field is true using aggregation framework

Synopsis 概要

Trying to count the number of times a user with the field 'seen' equals 'false' 尝试计算用户具有“看到”字段等于“假”的次数

(Mail) Collection Example (邮件)收集示例

{
 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
}

Java Method w/Mongo Aggregation Java方法/ Mongo聚合

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

What I've tried 我尝试过的

    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)))));

    }

Desired Result 所需结果

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


//Result : 3

You could try the following: 您可以尝试以下方法:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM