【问题标题】:Java Syntax for a Mongo Aggregation QueryMongo 聚合查询的 Java 语法
【发布时间】:2018-04-04 08:55:43
【问题描述】:

我被 Mongo 查询的 Java 语法卡住了。

我已经为控制台编写了 Mongo 查询,但我想要该查询的相应 Java 语法。

这是shell命令:

db.errorsegmentaudit.aggregate([
    {$sort:{timestamp:1}},
    {$limit:1},
    {$unwind:"$auditErrorTypeCounts"},
    {$unwind:"$auditErrorTypeCounts.auditErrorCounts"}, 
    {$group: {
            _id: {
                "agent": "$auditErrorTypeCounts.auditErrorCounts.agentName", 
                "type":"$auditErrorTypeCounts.typeOfError"
            }, 
            count: {
                $sum: "$auditErrorTypeCounts.auditErrorCounts.countOfErrors"
            }
        }    
    } 
])

我浏览了所有文档,但没有找到正确的文档。我尝试在 Java 中使用聚合类,但它不起作用。

【问题讨论】:

    标签: mongodb aggregation-framework mongodb-java


    【解决方案1】:

    与您问题中的 MongoDB shell 命令等效的 MongoDB Java 驱动程序(使用版本 3.x)是:

    MongoClient mongoClient = ...;
    
    MongoCollection<Document> collection = mongoClient.getDatabase("...").getCollection("..");
    
    AggregateIterable<Document> documents = collection.aggregate(Arrays.asList(
            // $sort:{timestamp:1}
            Aggregates.sort(Sorts.ascending("timestamp")),
    
            // $limit:1
            Aggregates.limit(1),
    
            // $unwind:"$auditErrorTypeCounts"
            Aggregates.unwind("$auditErrorTypeCounts"),
    
            // $unwind:"$auditErrorTypeCounts.auditErrorCounts"
            Aggregates.unwind("$auditErrorTypeCounts.auditErrorCounts"),
    
            // $group:{...}
            Aggregates.group(
                    // _id:{"agent":"$auditErrorTypeCounts.auditErrorCounts.agentName","type":"$auditErrorTypeCounts.typeOfError"}
                    new Document("agent", "$auditErrorTypeCounts.auditErrorCounts.agentName").append("type", "$auditErrorTypeCounts.typeOfError"),
    
                    // count:{$sum:"$auditErrorTypeCounts.auditErrorCounts.countOfErrors"}}}
                    Accumulators.sum("count", "$auditErrorTypeCounts.auditErrorCounts.countOfErrors")
            )
    ));
    

    聚合管道中每个阶段上方的 cmets 显示 Java 代码镜像哪个 shell 命令。例如:

    // $unwind:"$auditErrorTypeCounts.auditErrorCounts"
    Aggregates.unwind("$auditErrorTypeCounts.auditErrorCounts")
    

    ... 显示与 shell 命令 $unwind:"$auditErrorTypeCounts.auditErrorCounts" 等效的 Java 是 Aggregates.unwind("$auditErrorTypeCounts.auditErrorCounts")。这可能使您更容易将一个映射到另一个。

    更多详情请关注MongoDB Java driver docs

    【讨论】:

    • 感谢您的回答。我可以在 Spring 中使用 MongoOperation 做同样的事情吗?
    • 上述答案提供了从 shell 命令到 Java 驱动程序代码的映射。 Spring 的 MongoOperation 是 Java 驱动程序之上的一层,因此它可能有一些等价于 Aggregates
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-03-20
    • 1970-01-01
    • 2017-05-02
    • 2019-05-06
    • 2017-08-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多