Aggregate by hours in mongodb-async driver

How can I aggregate by hours in mongodb-async-driver ( http://www.allanbank.com/mongodb-async-driver/usage.html )

I have an ISODate field in my collection.

[
  { name = "a", date = ISODate(...)},
  { name = "b", date = ISODate(...)},
  ...
] 

      

I want to display a graph of how documents can occur per hour. in MongoDB console. I would do something like this:

db.mycollection.aggregate([{$group : {_id : {day:{ $hour : "$date"}}, count: { $sum: 1 }}}])

      

but i'm stuck in driver-api:

 import static com.allanbank.mongodb.builder.AggregationGroupField.set;
 import static com.allanbank.mongodb.builder.AggregationGroupId.id;

 Aggregate.Builder builder = new Aggregate.Builder();
 builder.group(id().add(???), set("pop").sum("pop"))

      

+3


source to share


1 answer


You need to use the Expressions class . Use a method group

that takes an array Builder

and as input AggregationGroupField

.

public Aggregate.Builder group(AggregationGroupId.Builder id,
                      AggregationGroupField... aggregations)

      



Create an expression hour

and pass it as an identifier.

    Builder hour = new Builder();
    hour.add(Expressions.set("day",Expressions.hour(Expressions.field("date"))));
    Aggregate.Builder builder = Aggregate.builder();
    builder.group(
       hour,
       AggregationGroupField.set("pop").sum("pop")
      );
    MongoIterator<Document> result = col.aggregate(builder);
    while(result.hasNext())
    {
        System.out.println(result.next());
    };

      

+2


source







All Articles