Count results with MongoDB 3.0 Java Driver -


i want number of results of query. want know how users online in past 15 minutes. so, set connection with:

mongoclient = new mongoclient("localhost", 3001); database = mongoclient.getdatabase("database1"); 

then in method collection , send query...:

mongocollection<document> users = database.getcollection("users"); users.find(and(gte("lastlogin",xvminago),lte("lastlogin",now) 

i'm not sure if last step right. seems easy in javascript , .count()-opereration can't find in java. , documentation(s), weird , somehow diffrent. (i use mongodb java driver 3.0)

use mongocollection's count() method, applying query filter makes use of datetime object joda-time library simplifies date manipulation in java. can check out here. create datetime object 15 minutes current time:

datetime dt = new datetime(); datetime = new datetime(); datetime subtracted = dt.minusminutes(15); 

then use variables construct date range query use in count() method:

document query = new document("lastlogin", new document("$gte", subtracted).append("$lte", now)); mongoclient = new mongoclient("localhost", 3001); long count = mongoclient.getdatabase("database1")                         .getcollection("users")                         .count(query); 

on sharded cluster, underlying db.collection.count() method can result in inaccurate count if orphaned documents exist or if chunk migration in progress. it's safer use aggregate() method instead:

iterator<document> = mongoclient.getdatabase("database1")                        .getcollection("users")                        .aggregate(arrays.aslist(                             new document("$match", new document("lastlogin",                                  new document("$gte", subtracted).append("$lte", now))                             ),                             new document("$group", new document("_id", null)                                 .append("count",                                      new document("$sum", 1)                                 )                             )                         )                     ).iterator(); int count = it.hasnext() ? (integer)it.next().get("count") : 0; 

Comments

Popular posts from this blog

javascript - Slick Slider width recalculation -

jsf - PrimeFaces Datatable - What is f:facet actually doing? -

angular2 services - Angular 2 RC 4 Http post not firing -