spring中聚合中mongo数组投影后为空

ecbunoof  于 2023-08-02  发布在  Spring
关注(0)|答案(1)|浏览(97)

这是我在Mongo的最后一个阶段:

{
  name: 1,
  items: "$activeItems",
  tables: {
    "$map": {
      "input": "$activeTables",
      "as": "table",
      "in": {
        "tableName": "$$table.tableName",
        "tableId": "$$table.tableId"

字符串
我在Spring Data 中这样写:

final var projectStage = Aggregation.project()
        .andInclude("name")
        .andExpression("$activeItems").as("items")
        .and(VariableOperators.Map.itemsOf("$activeTables").as("table")
                .andApply(doc -> {
                    Document document = new Document();
                    document.append("tableName", "$$table.tableName");
                    document.append("tableId", "$$table.tableId");
                    return document;
                }))
        .as("tables");

    final var result = mongoTemplate.aggregate(aggregation, Something.class, SomethingDto.class);


实体定义为

@Document(collection = "#{@mongoProperties.getSomethingCollectionName()}")
@TypeAlias("something")
public class Something{ 
    @Id
    private String id;
    private String name;
    private List<SomethingElseIdDto> somethingElse;
    private List<Long> tables;
}


DTO是普通的POJO:

public class SomethingDto {
    String name;
    List<ItemDto> items;
    List<TableDto> tables;
}

@Data
@Builder(toBuilder = true)
@AllArgsConstructor
public class ItemDto {
    Long itemId;
    String itemName;


当运行Sping Boot 应用程序时,我从REST端点获取完整的数据,包括itemstables数组。但是集成测试发现tablesitems两个数组都是空的。我在Compass中验证了它们是在Mongo中计算的,即使在测试集合中也是如此。

@SpringBootTest
@ActiveProfiles({"test", "integration-test"})
class DbServiceTest {


样本数据:

{
    "name": "XYZ",
    "items": [
        {
            "itemId": 123,
            "itemName": "A",
        },
    "tables": [
        {
            "tableId": 456,
            "tableName": "Q",
        },


这太奇怪了相同的代码会根据Spring轮廓产生不同的结果。

pengsaosao

pengsaosao1#

好吧,问题是集合也必须动态计算:

final var resolvedStage = Aggregation.lookup(mongoProperties.getSomethingCollectionName()(),
            "something.id", "id", "items");

字符串

相关问题