Search code examples
arraysmongodbmeteornested

MongoDB : return a list of all subdocument


I'm trying to learn Meteor/Mongo, but each time you think to make progress, a "simple thing" seems totally beyond reach...

I have a very simple document :

_id   : abcd
field : xyz
subdoc [
  {_id: 123, email: abc, name: abc}
  {_id: 234, email: abc, name: xyz}
  {_id: 853, email: abc, name: pmu}
]

And I want to return a list of all my subdocuments. Put in another word, I'd like to get a list like this one, in my HTML template using "each":

  _id: 123    email: abc    name: abc
  _id: 234    email: abc    name: xyz
  _id: 853    email: abc    name: pmu

But I'm totally unable to achieve any results with .dot notation.. Any clue?

Thanks a lot..


Solution

  • myCollection.find({_id: 'abcd'}).fetch().forEach(function(item) { return item.subdoc; });
    

    or even simpler with findOne

    myCollection.findOne({_id: 'abcd'}).subdoc;
    

    Note:

    In the 2 cases only one document is returned by the _id (since _id is unique) you will get the subdoc array.

    If you use the first solution and your query returns multiple documents, then you will get an array of Arrays.

    If what you want is a flat array from the array of Arrays, you need to flatten that array

    with underscore that would be

    flattened = _.flatten(nestedArray)