MongoDB - how to join parent and child products by reference

Posted by Jaro on Stack Overflow See other posts from Stack Overflow or by Jaro
Published on 2013-11-09T15:00:00Z Indexed on 2013/11/09 15:54 UTC
Read the original article Hit count: 282

Filed under:
|

my mongo collection stores products. There are two product types: child and parent. Parent product holds array of its child as reference.

Use case:

use mydb;

child1 = {
    _id: 1,
    name: "Child 1",
    is_child: true,
    is_parent: false,
    children : []
}

child2 = {
    _id: 2,
    name: "Child 2",
    is_child: true,
    is_parent: false,
    children : []
}

parent = {
    _id: 3,
    name: "Parent product",
    is_child: false,
    is_parent: true,
    children : [1, 2]
}

db.product.insert( [child1, child2, parent] );

And I'm looking for any query returning

{
    _id: 3,
    name: "Parent product",
    is_child: false,
    is_parent: true,
    children: [
        {
            _id: 1,
            name: "Child 1",
            is_child: true,
            is_parent: false,
            children : []
        },
        {
            _id: 2,
            name: "Child 2",
            is_child: true,
            is_parent: false,
            children : []
        }
    ] 
}

I'm newbie to mongodb, but I guess an usage of map-reduce could solve the problem. Can anyone advice? Thx

© Stack Overflow or respective owner

Related posts about mongodb

Related posts about mongodb-query