MongoDB + Spring:聚合多个分组和求和

问题描述 投票:0回答:1

我有我的 MongoDB 查询,它返回预期的数据,但我正在努力用 Spring (org.springframework.data.mongodb.core.MongoTemplate) 翻译它。

假设在我的收藏 A 中我有这份文件

{
    "_id" : ObjectId("12345"),
    "name" : "someCoolName",
    "updatedAt" : ISODate("2023-03-15T17:35:00.000Z"),
    "notes" : [ 
        {
            "description" : "A lot of description",
            "dueDate" : ISODate("2023-03-07T09:35:00.000Z"),
            "counter" : 0
        }, 
        {
            "description" : "Bit less description",
            "dueDate" : ISODate("2023-03-15T17:35:00.000Z"),
            "counter" : 1
        }, 
    ]
}

在我的收藏 B 中,我有这个链接文档

{
    "_id" : ObjectId("67890"),
    "idNotes" : ObjectId("12345"), //id of document from collection A
    "counter" : 0,
    "review" : "amazing"
}

我建立了一个查询,提取所有文档,其中注释的数组大小与 idNotes 在集合 B 中找到的结果数不匹配。 这是我的 MongoDB 查询:

db.collectionA.aggregate([
{ $lookup: {
  from: 'collectionB',
  localField: '_id',
  foreignField: 'idNotes',
  as: 'documentB'
}}, 
{ $group: {
  _id: "$_id",
  fromB: { $sum: { $cond: { if: { $isArray: "$documentB" }, then: { $size: "$documentB" }, else: 0} }},
  numberOfNotes: {$sum: {$cond: { if: { $isArray: "$notes" }, then: { $size: "$notes" }, else: 0} }}, 
"updatedAt": { $first: "$updatedAt" }
}},
{ $match: {
  $expr: {$ne: ["$fromB", "$numberOfNotes"]}
}},
{ $sort : { "updatedAt" : -1 }}
])

你能帮我吗?我被这样的事情困住了

GroupOperation groupOperation = Aggregation.group("documentB").sum("$size: documentB").as("fromB");

但我不明白如何/什么是添加其他 groupBy 条件的最佳方法。

在此先感谢您,我们将不胜感激。

spring mongodb aggregation-framework spring-data spring-mongodb
1个回答
1
投票

我想你可以尝试这样的事情:

GroupOperation groupOperation = Aggregation.
    group("_id")
        .sum("fromB",
            cond(isArray("documentB"),size("documentB"),0)
        ).as("fromB")
        .sum("numberOfNotes",
            cond(isArray("notes"),size("notes"),0)
        ).as("numberOfNotes")
        .first("updatedAt").as("updatedAt");
© www.soinside.com 2019 - 2024. All rights reserved.