使用MongoDB 3.0 Java驱动程序计算结果 [英] Count results with MongoDB 3.0 Java Driver
问题描述
我只想获得一些查询的结果数量。具体来说,我想知道过去15分钟内有多少用户在线。所以,我设置连接:
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)
我甚至不确定最后一步是否正确。但是在Javascript和.count()中这似乎很容易 - 我在Java中找不到的操作。以及文档,是奇怪的,不知何故都不同。(我使用MongoDB Java驱动程序3.0)
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)
推荐答案
使用MongoCollection的 count( )
方法,应用查询过滤器,该过滤器使用 Joda-Time 库,简化了java中的日期操作。你可以查看 这里 。基本上是创造e当前时间15分钟的日期时间对象:
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);
然后使用变量构造日期范围查询以在count()方法中使用:
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);
在分片群集中,基础 db.collection.count()
方法可能导致计数不准确。因此,使用 aggregate()$更安全c $ c>
方法:
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;
这篇关于使用MongoDB 3.0 Java驱动程序计算结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!