2015-11-01 52 views
2

我只想获得一些查询的结果数量。具体而言,我想知道过去15分钟内有多少用户在线。所以,我设置连接了:使用MongoDB 3.0 Java驱动程序计算结果

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

然后在我的方法,我得到的收集和发送查询...:

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

我甚至不知道,如果最后一步是对。但是,在Javascript和这个.count() - 我无法在Java中找到的opereration看起来很容易。和文件,是奇怪的,总之不同。 (我使用MongoDB的Java驱动程序3.0)

回答

4

使用MongoCollection的count()方法,应用查询过滤器,这使得从简化日期操作Java中的Joda-Time库使用datetime对象。你可以检查出来here。基本上从当前时间创建日期时间物体15分:

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

然后使用变量来构造用于使用的日期范围的查询中的计数()方法:

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<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; 
相关问题