[英]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.