Count results with MongoDB 3.0 Java Driver

后端 未结 1 386
情深已故
情深已故 2021-01-22 13:36

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:

相关标签:
1条回答
  • 2021-01-22 14:38

    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;
    
    0 讨论(0)
提交回复
热议问题