簡體   English   中英

使用Java驅動程序進行MongoDB聚合

[英]MongoDB aggregation with Java driver

我需要你幫助將MongoDB聚合框架與java驅動程序一起使用。 即使有這個文檔 ,我也不明白如何編寫我的請求。

我想從我的收藏中的所有項目中獲取200個最舊的視圖。 這是我的mongo查詢(在控制台模式下工作方式如下):

db.myCollection.aggregate(
    {$unwind : "$views"},
    {$match : {"views.isActive" : true}},
    {$sort : {"views.date" : 1}},
    {$limit : 200},
    {$project : {"_id" : 0, "url" : "$views.url", "date" : "$views.date"}}
)

此集合中的項目具有一個或多個視圖。 我的問題不是關於請求結果,我想知道java語法。

終於找到了解決方案,我得到的結果與原始請求相同。

Mongo Driver 3:

匯總文件

MongoCollection<Document> collection = database.getCollection("myCollection");

AggregateIterable<Document> output = collection.aggregate(Arrays.asList(
        new Document("$unwind", "$views"),
        new Document("$match", new Document("views.isActive", true)),
        new Document("$sort", new Document("views.date", 1)),
        new Document("$limit", 200),
        new Document("$project", new Document("_id", 0)
                    .append("url", "$views.url")
                    .append("date", "$views.date"))
        ));

// Print for demo
for (Document dbObject : output)
{
    System.out.println(dbObject);
}

您可以使用靜態導入使其更具可讀性:
import static com.mongodb.client.model.Aggregates.*;
請參閱koulini回答complet示例

Mongo Driver 2:

匯總文件

Iterable<DBObject> output = collection.aggregate(Arrays.asList(
        (DBObject) new BasicDBObject("$unwind", "$views"),
        (DBObject) new BasicDBObject("$match", new BasicDBObject("views.isActive", true)),
        (DBObject) new BasicDBObject("$sort", new BasicDBObject("views.date", 1)),
        (DBObject) new BasicDBObject("$limit", 200),
        (DBObject) new BasicDBObject("$project", new BasicDBObject("_id", 0)
                    .append("url", "$views.url")
                    .append("date", "$views.date"))
        )).results();

// Print for demo
for (DBObject dbObject : output)
{
    System.out.println(dbObject);
}

查詢轉換邏輯: 查詢轉換邏輯 感謝這個鏈接

值得指出的是,通過使用MongoDB的Java聚合方法,您可以大大改善這里的答案所顯示的代碼。

讓我們以代碼為例,OP回答他自己的問題。

AggregateIterable<Document> output = collection.aggregate(Arrays.asList(
        new Document("$unwind", "$views"),
        new Document("$match", new Document("views.isActive", true)),
        new Document("$sort", new Document("views.date", 1)),
        new Document("$limit", 200),
        new Document("$project", new Document("_id", 0)
                    .append("url", "$views.url")
                    .append("date", "$views.date"))
));

我們可以重寫上面的代碼如下;

import static com.mongodb.client.model.Aggregates.*;

AggregateIterable output = collection.aggregate(Arrays.asList(
                unwind("$views"),
                match(new Document("views.isActive",true)),
                sort(new Document("views.date",1)),
                limit(200),
                project(new Document("_id",0)
                        .append("url","$views.url")
                        .append("date","$views.date"))
));

顯然,您將需要相應的靜態導入,但除此之外,第二個示例中的代碼更清晰更安全 (因為您不必每次都自己鍵入運算符),更可讀和更美觀的 IMO。

使用前面的示例作為指南,以下是使用mongo驅動程序3及以上的方法:

MongoCollection<Document> collection = database.getCollection("myCollection");
AggregateIterable<Document> output = collection.aggregate(Arrays.asList(
    new Document("$unwind", "$views"),
    new Document("$match", new Document("views.isActive", true))
));

for (Document doc : output) {
    ...
}

這是一種通過departmentId統計員工的簡單方法。詳細信息: 使用Java API進行聚合

        Map<Long, Integer> empCountMap = new HashMap<>();

        AggregateIterable<Document> iterable = getMongoCollection().aggregate(Arrays.asList(
                new Document("$match",
                        new Document("active", Boolean.TRUE)
                                .append("region", "India")),
                new Document("$group",
                        new Document("_id", "$" + "deptId").append("count", new Document("$sum", 1)))));

        iterable.forEach(new Block<Document>() {
            @Override
            public void apply(final Document document) {
                empCountMap.put((Long) document.get("_id"), (Integer) document.get("count"));
            }
        });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM