弹簧数据 mongodb 层次结构



我在分层结构中有一个嵌套的 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 的春季数据。

你可以试试下面的聚合。

$redact一次遍历文档级别,并对匹配条件执行$$DESCEND$$PRUNE

$unwind带有preserveNullAndEmptyArrays$childCategory,以保持数组具有null值。

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

最新更新