创建聚合管道时,累加器操作器最大值出现问题

jum4pzuy  于 2021-06-29  发布在  Java
关注(0)|答案(1)|浏览(385)

我正在尝试将以下mongo shell聚合查询转换为spring数据mongodb聚合:

db.getCollection('Orders').aggregate([
{ $group: {
    "_id": {"book":"$bookingId"},
    "docs": {$push: '$$ROOT'}
  }
},
{$project: {
   latestOrd: {
      $filter: {
         input: "$docs",
         as: "item",
         cond: { $eq: ["$$item.bookingVersion", { $max: "$docs.bookingVersion" }] }
      }
   }
 }
},
{ $unwind: "$latestOrd" },
{ $replaceRoot:{newRoot:"$latestOrd"}}
])

查询获取具有最高预订版本的所有订单(例如,一个bookingid可能有许多具有版本3的文档)。
此查询在mongo shell中运行良好,但我对它的spring数据版本有异议:

Aggregation.group("bookingId").push(Aggregation.ROOT).as("docs");
Aggregation.project().and(filter("docs")
          .as("item")
          .by(valueOf("item.bookingVersion")
                .equalToValue(AccumulatorOperators.Max.maxOf("docs.bookingVersion"))))
          .as("latestOrd");
Aggregation.unwind("latestOrd");
Aggregation.replaceRoot("latestOrd");

spring生成的mongo查询与我上面提供的查询类似,除了$max accumulator:

{ "$max" : "$$docs.bookingVersion" }

由于某些原因,它添加了双美元符号而不是单美元符号,因此我有以下错误:

'Use of undefined variable: docs' on server 127.0.0.1:27017

我使用的是springbootstarter2.1.0.release和mongo服务器的4.2版本。我很感激你在这方面的帮助。
输入文件:

[
  {
    "_id": "5f847811ebcd1a51a0196736",
    "status": "REJECTED",
    "bookingId": "1",
    "bookingVersion": 4,
    "operation": "CREATE"
  },
  {
    "_id": "5f847811ebcd1a51a0196735",
    "status": "CREATED",
    "bookingId": "1",
    "bookingVersion": 4,
    "docNumber": "7",
    "operation": "CREATE"
  },
  {
    "_id": "5f847811ebcd1a51a0196734",
    "status": "CREATED",
    "bookingId": "1",
    "bookingVersion": 3,
    "docNumber": "6",
    "operation": "CREATE"
  },
  {
    "_id": "5f847811ebcd1a51a0196738",
    "status": "CREATED",
    "bookingId": "2",
    "bookingVersion": 1,
    "docNumber": "8",
    "operation": "CREATE"
  },
  {
    "_id": "5f847811ebcd1a51a0196737",
    "status": "CREATED",
    "bookingId": "2",
    "bookingVersion": 2,
    "docNumber": "9",
    "operation": "CREATE"
  }
]

预期产量:

[
  {
    "_id": "5f847811ebcd1a51a0196736",
    "status": "REJECTED",
    "bookingId": "1",
    "bookingVersion": 4,
    "operation": "CREATE"
  },
  {
    "_id": "5f847811ebcd1a51a0196735",
    "status": "CREATED",
    "bookingId": "1",
    "bookingVersion": 4,
    "docNumber": "7",
    "operation": "CREATE"
  },
  {
    "_id": "5f847811ebcd1a51a0196737",
    "status": "CREATED",
    "bookingId": "2",
    "bookingVersion": 2,
    "docNumber": "9",
    "operation": "CREATE"
  }
]
kuuvgm7e

kuuvgm7e1#

问题可能出在SpringBoot的2.1.0.release版本上,但升级它不是我的选择。为了实现这一点,我创建了aggregationexpression,而不是 AccumulatorOperators.Max.maxOf("docs.bookingVersion") 部分。
这里有一个方法:

private AggregationExpression buildMaxExpression() {
    return new AggregationExpression() {
      @Override
      public Document toDocument(final AggregationOperationContext context) {
        return new Document("$max", "$docs.bookingVersion");
      }
    };
  }

相关问题