【问题标题】:Spring data mongodb hierarchySpring数据MongoDB层次结构
【发布时间】:2017-02-09 03:41:27
【问题描述】:

我有一个嵌套在下面定义的层次结构中的 json 对象

[
    {
        "categoryId": 1,
        "categoryName": "Category 1",
        "childCategory": null,
        "active": false
    },
    {
        "categoryId": 2,
        "categoryName": "Category 2",
        "active": true,
        "childCategory": [
            {
                "categoryId": 4,
                "categoryName": "Category 4",
                "childCategory": null,
                "active": false
            },
            {
                "categoryId": 5,
                "categoryName": "Category 5",
                "childCategory": null,
                "active": true
            }
        ]
    },
    {
        "categoryId": 10,
        "categoryName": "Category 10",
        "childCategory": null,
        "active": true
    }
]

从此我想将所有活动类别选择到单个数组结构中。我的输出应该是

[
    {
        "categoryId": 2,
        "categoryName": "Category 2",
        "active": true
    },
    {
        "categoryId": 5,
        "categoryName": "Category 5",
        "active": true
    },
    {
        "categoryId": 10,
        "categoryName": "Category 10",
        "active": true
    }
]

是否可以在单个查询语句中直接获取此数据。我正在为 mongodb 使用 spring 数据。

【问题讨论】:

    标签: mongodb mongodb-query aggregation-framework spring-data-mongodb


    【解决方案1】:

    您可以尝试以下聚合。

    $redact 一次遍历一个文档级别并根据匹配条件执行$$DESCEND$$PRUNE

    $unwind $childCategorypreserveNullAndEmptyArrays 以保留具有 null 值的数组。

    db.collection.aggregate({
        $redact: {
            $cond: [{
                $eq: ["$active", true]
            }, "$$DESCEND", "$$PRUNE"]
        }
    }, {
        $unwind: {
            path: "$childCategory",
            preserveNullAndEmptyArrays: true
        }
    })
    

    【讨论】:

      猜你喜欢
      • 2016-09-06
      • 2011-08-27
      • 1970-01-01
      • 2020-03-10
      • 1970-01-01
      • 2015-12-16
      • 2012-12-28
      • 2019-06-08
      • 1970-01-01
      相关资源
      最近更新 更多