0

I have a nested json object in a hierarchical structure as defined below

[
    {
        "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
    }
]

From this I want to select all the active categories to a single array structure. My output should be

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

Is it possible to directly fetch this data in a single query statement. I am using spring data for mongodb.

1 Answer 1

1

You can try below aggregation.

$redact to go through a document level at a time and perform $$DESCEND and $$PRUNE on the matching criteria.

$unwind the $childCategory with preserveNullAndEmptyArrays to keep the array with null values.

db.collection.aggregate({
    $redact: {
        $cond: [{
            $eq: ["$active", true]
        }, "$$DESCEND", "$$PRUNE"]
    }
}, {
    $unwind: {
        path: "$childCategory",
        preserveNullAndEmptyArrays: true
    }
})
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.