Spring 数据 mongodb 层级
Spring data mongodb hierarchy
我在层次结构中有一个嵌套的 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
}
]
据此我想 select 所有活动类别到一个数组结构。我的输出应该是
[
{
"categoryId": 2,
"categoryName": "Category 2",
"active": true
},
{
"categoryId": 5,
"categoryName": "Category 5",
"active": true
},
{
"categoryId": 10,
"categoryName": "Category 10",
"active": true
}
]
是否可以在单个查询语句中直接获取此数据。我正在为 mongodb.
使用 spring 数据
您可以尝试以下聚合。
$redact
一次遍历文档级别并对匹配条件执行 $$DESCEND
和 $$PRUNE
。
$unwind
$childCategory
和 preserveNullAndEmptyArrays
以保持数组具有 null
值。
db.collection.aggregate({
$redact: {
$cond: [{
$eq: ["$active", true]
}, "$$DESCEND", "$$PRUNE"]
}
}, {
$unwind: {
path: "$childCategory",
preserveNullAndEmptyArrays: true
}
})
我在层次结构中有一个嵌套的 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
}
]
据此我想 select 所有活动类别到一个数组结构。我的输出应该是
[
{
"categoryId": 2,
"categoryName": "Category 2",
"active": true
},
{
"categoryId": 5,
"categoryName": "Category 5",
"active": true
},
{
"categoryId": 10,
"categoryName": "Category 10",
"active": true
}
]
是否可以在单个查询语句中直接获取此数据。我正在为 mongodb.
使用 spring 数据您可以尝试以下聚合。
$redact
一次遍历文档级别并对匹配条件执行 $$DESCEND
和 $$PRUNE
。
$unwind
$childCategory
和 preserveNullAndEmptyArrays
以保持数组具有 null
值。
db.collection.aggregate({
$redact: {
$cond: [{
$eq: ["$active", true]
}, "$$DESCEND", "$$PRUNE"]
}
}, {
$unwind: {
path: "$childCategory",
preserveNullAndEmptyArrays: true
}
})