繁体   English   中英

使用MongoDB 3.0 Java驱动程序计数结果

[英]Count results with MongoDB 3.0 Java Driver

我只想获取一些查询结果的数量。 我特别想知道过去15分钟内有多少用户在线。 因此,我通过以下方式建立了连接:

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中却找不到。 而且这些文档很奇怪,而且全都有些不同。 (我使用MongoDB Java驱动程序3.0)

使用MongoCollection的count()方法,应用查询过滤器,该过滤器利用Joda-Time库中的Datetime对象简化了Java中的日期操作。 您可以在这里查看 基本上是从当前时间开始15分钟创建一个datetime对象:

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

然后使用变量构造一个日期范围查询,以供count()方法使用:

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;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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