【问题标题】:Flatten nested arrays using mongodb aggregation in spring在春季使用 mongodb 聚合展平嵌套数组
【发布时间】:2020-04-17 08:38:45
【问题描述】:

我正在尝试使用聚合框架来展平嵌套数组,但我无法得到结果。 我的收藏是:

[
    {
        "id" : "xxx",
        "countryName" : "xxx",
        "cities" : [
            {
                "id" : "xxx",
                "cityName" : "xxx"
            },
            {
                "id" : "xxx",
                "cityName" : "xxx"
            }
        ]
    }
]

我想得到所有国家的城市,我要找的结果是:

[
    {
        "id" : "xxx",
        "cityName" : "xxx"
    },
    {
        "id" : "xxx",
        "cityName" : "xxx"
    }
]

我尝试了这个请求:

val aggregation = Aggregation.newAggregation(
                Aggregation.group("cities")
        )

return mongoDb.aggregate(aggregation, Country::class.java, Any::class.java).mappedResults

但是,我得到了这个结果:

[
    {
        "_id": [
            {
                "id": "xxx",
                "cityName": "xxx"
            },
            {
                "id": "xxx",
                "cityName": "xxx"
            }
        ]
    }
]

有人可以帮帮我吗?

【问题讨论】:

    标签: java mongodb kotlin spring-data aggregation-framework


    【解决方案1】:

    此聚合将帮助您实现结果,但您必须使用 Java 驱动程序对其进行调整:

    db.countries.aggregate([
      {
        "$unwind": "$cities"
      },
      {
        "$project": {
          "_id": 0,
          "cities": 1
        }
      },
      {
        "$replaceRoot": {
          "newRoot": "$cities"
        }
      }
    ])
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-07-26
      • 1970-01-01
      • 2022-07-06
      • 2021-06-27
      • 2017-07-16
      • 1970-01-01
      • 1970-01-01
      • 2021-07-20
      相关资源
      最近更新 更多