1

Suppose there is a document, that contains an array of documents each of which in turn contains an array of documents, like

{_id: 1, level1: [
  {_id: 10, level2: [
    {_id: 100},
    {_id: 101},
    {_id: 102},
  ]},
  {_id: 11, level2: [
    {_id: 103},
    {_id: 104},
    {_id: 105},
  ]},
  {_id: 12, level2: [
    {_id: 106},
    {_id: 107},
    {_id: 108},
  ]}
]}

and there is an _id = 101 of some inner (third level) document, that I want to search for. I would like to get the inner document and all the enclosing documents in one result, i.e.

{
  doc1: {_id: 1, level1: [
          {_id: 10, level2: [
            {_id: 100},
            {_id: 101},
            {_id: 102},
          ]},
          {_id: 11, level2: [
            {_id: 103},
            {_id: 104},
            {_id: 105},
          ]},
          {_id: 12, level2: [
            {_id: 106},
            {_id: 107},
            {_id: 108},
          ]}
        ]},

  doc2: {_id: 10, level2: [
          {_id: 100},
          {_id: 101},
          {_id: 102},
        ]},

  doc3: {_id: 101}
}

Is it possible to achieve this using the Aggregation Framework?

1
  • Are there always three levels to your documents, or are you looking for some sort of recursive query? The aggregation framework (as at MongoDB 2.6) doesn't support any form of recursion, but if you have a fixed document structure you could perhaps use multiple $unwind and $group steps to get your desired end result. I suspect what you're actually trying to do is Model Tree Structures in MongoDB, and there would be a better way to structure your schema.
    – Stennie
    Jul 3, 2014 at 13:38

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.