2015-11-01 54 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; 
相關問題