简体   繁体   中英

Count results with MongoDB 3.0 Java Driver

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:

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

Then in my method i get the collection and send a query...:

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

I'm not even sure if the last step is right. But it seems so easy in Javascript and this .count()-opereration which I can't find in Java. And the documentation(s), are weird and somehow all diffrent. (I use the MongoDB Java Driver 3.0)

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM