Auto-Reference in MongoDB

4

I have a collection which has a parent field that refers to documents from the same collection, now what I do is call them and find the id of the parent and create a children field where all the subdocuments go, this I do in the controller with an order and I do not know how to make the Database, I think it could be with a mapReduce but I'm not sure how it is done.

My collection looks like this:

0:{
    id:1,
    nombre:'pepito perez'
},
1:{
    id:2,
    nombre:'jony se',
    padre:1 
},
2:{
    id:3,
    nombre:'rojas del totaso'
},
3:{
    id:4,
    nombre:'rosa melano'
    padre:3 
}

What I want to achieve is the following:

0:{
    id:1,
    nombre:'pepito perez'
    hijos:[
    {
        id:2,
        nombre:'jony se',
        padre:1 
    }
    ]
},
1:{
    id:3,
    nombre:'rojas del totaso',
    hijjos:[
        {
            id:4,
            nombre:'rosa melano'
            padre:3 
        }
    ]
}

Thank you in advance

    
asked by soldat25 21.12.2015 в 16:19
source

1 answer

1

Structure with reference to parents

The following example stores the reference to the parent category in the parent field:

db.categories.insert( { _id: "MongoDB", parent: "Databases" } )
db.categories.insert( { _id: "dbm", parent: "Databases" } )
db.categories.insert( { _id: "Databases", parent: "Programming" } )
db.categories.insert( { _id: "Languages", parent: "Programming" } )
db.categories.insert( { _id: "Programming", parent: "Books" } )
db.categories.insert( { _id: "Books", parent: null } )
  • The query retrieves the immediate children of a node is fast and simple:

    db.categories.findOne( { _id: "Databases" } ).children

  • You can create an index for the children field to enable a quick search by child nodes :

    db.categories.createIndex( { children: 1 } )

  • You can query a child node to find its parent node, as well as its siblings:

    db.categories.find( { children: "MongoDB" } )

You can also do the opposite, I leave you official information of where I got the answer (English). I hope you support:

answered by 21.12.2015 / 22:10
source