2

I'm new to mongodb and mongoose and I'm having trouble just getting a sub sub array.

My data is like this:

    [
     {_id : ...,
     name : 'Category name1',
     products : [
                    {
                    code : 'zxcv'
                    name : 'T-Shirt 1',
                    items : [
                          {code:'zxcv', size : 'S'}
                          {code:'zxcv', size : 'M'}
                          {code:'zxcv', size : 'L'}
                          {code:'zxcv', size : 'XL'}

                        ]
                     },
                     {
                    code : 'qwerty'
                    name : 'T-Shirt 2',
                    items : [
                          {code:'qwerty', size : 'S'}
                          {code:'qwerty', size : 'M'}
                          {code:'qwerty', size : 'L'}
                          {code:'qwerty', size : 'XL'}

                        ]
                     }
                 ]
            },
            {_id : ...,
             name : 'Category name2',
             products : [ ... ]
             }
        ]

I want to get just the products where the code = 'zxcv'

If I do:

ProductGroup.find({'products.code' : 'zxcv'},function(err, products){})

I get all of the first product category - not just the products that have code = 'zxcv'

user2890027
  • 321
  • 2
  • 13
  • possible duplicate of [MongoDB extract only the selected item in array](http://stackoverflow.com/questions/3985214/mongodb-extract-only-the-selected-item-in-array) – JohnnyHK Mar 05 '14 at 15:15

1 Answers1

7

I figured it out. Since I spend hours searching for an answer and couldn't find one, maybe this will help another noob with the same problem:

To get just the products that match:

ProductGroup.find({'products.code' : 'zxcv'},'products.code.$.items', function(err, products){})
user2890027
  • 321
  • 2
  • 13