I just want to get the number of results of some query. Specifically I want to know how much users were online in the past 15 minutes. So, I set the connection up with:
Use MongoCollection's count() method, applying a query filter which makes use of the Datetime object from the Joda-Time library that simplifies date manipulation in java. You can check that out here. Basically create a datetime object 15 minutes from current time:
DateTime dt = new DateTime();
DateTime now = new DateTime();
DateTime subtracted = dt.minusMinutes(15);
Then use the variables to construct a date range query for use in the 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 a sharded cluster, the underlying db.collection.count() method can result in an inaccurate count if orphaned documents exist or if a chunk migration is in progress. So it's safer to use aggregate() method instead:
Iterator<Document> it = 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;