Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

I'm still confused which structure is better structure using MongoDB.

Place child in parent:

{
    "_id": "528ba7691738025d11aab772",
    "post": "Hello 1",
    "childs": [
        {
            "_id": "528ba7691738025d11aab555",
            "post": "Hello 2",
            "childs": []
        },
        {
            "_id": "528ba7691738025d117631783",
            "post": "Hello 22",
            "childs": [
                {
                    "_id": "528ba7612D38025d11aab772",
                    "post": "Hello 3",
                    "childs": []
                }
            ]
        }
    ]
}

Place child equal with the parent like relational database do:

[
    {
        "_id": "528ba7691738025d11aab772",
        "post": "Hello 1",
        "parent_id": null
    },
    {
        "_id": "528ba7691738025d11aab555",
        "post": "Hello 2",
        "parent_id": "528ba7691738025d11aab772"
    },
    {
        "_id": "528ba7691738025d117631783",
        "post": "Hello 22",
        "parent_id": "528ba7691738025d11aab772"
    },
    {
        "_id": "528ba7612D38025d11aab772",
        "post": "Hello 3",
        "parent_id": "528ba7691738025d117631783"
    }
]
share|improve this question

1 Answer 1

in general, arrays nested in arrays are going to limit your db operations, specifically in update operations.

I would refrain from using them, so option 1 seems impractical to me

there will never be a right answer for all cases, as the parent-child problems relies heavily on your access patterns (i.e. whether you usually access the parent through the child or vice versa)

that is, if your application would usually find all children by a parent, i would keep an array of child Ids in the parent object (keep it at parent-child level, no grandchildren!)

there's always the denormalized alternative, of keeping a bi-directional reference where a parent keeps an array of children, and the child keeps a parent Id

so, the bottom line is you should think ahead about the aforementioned access pattern and make a decision based on that.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.