使用MongoDB 3.0 Java驱动程序计算结果

我只是想获得一些查询的结果数量。 具体来说,我想知道过去15分钟内有多少用户在线。 所以,我设置连接:

mongoClient = new MongoClient("localhost", 3001); database = mongoClient.getDatabase("database1"); 

然后在我的方法中我得到集合并发送查询…:

 MongoCollection users = database.getCollection("users"); users.find(and(gte("lastlogin",xvminago),lte("lastlogin",now) 

我甚至不确定最后一步是否正确。 但是在Javascript和.count()中这似乎很容易 – 我在Java中找不到的操作。 而文档是奇怪的,并且不知何故都是不同的。 (我使用MongoDB Java Driver 3.0)

使用MongoCollection的count()方法,应用一个查询filter,该filter利用Joda-Time库中的Datetime对象,简化了java中的日期操作。 你可以在这里查看 。 基本上创建一个距当前时间15分钟的日期时间对象:

 DateTime dt = new DateTime(); DateTime now = new DateTime(); DateTime subtracted = dt.minusMinutes(15); 

然后使用变量构造日期范围查询以在count()方法中使用:

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

在分片群集上,如果存在孤立文档或正在进行块迁移,则基础db.collection.count()方法可能导致计数不准确。 因此,使用aggregate()方法更安全:

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