title: Filtering an array inside an array in Mongo DB
body: <p>I want to filter an array inside an array in Mongo DB. For example, given these 2 documents:</p>
  
  <pre><code>{ 
  "_id" : 1.0, 
  "pages" : [
      {
          "texts" : [
              {
                  "text" : "foo"
              }, 
              {
                  "text" : "foo1"
              }, 
              {
                  "text" : "foo2"
              }
          ]
      }
  ]
  }
  { 
  "_id" : 2.0, 
  "pages" : [
      {
          "texts" : [
              {
                  "text" : "bar"
              }, 
              {
                  "text" : "bar1"
              }, 
              {
                  "text" : "bar2"
              }
          ]
      }
  ]
  }
  </code></pre>
  
  <p>I want a query that finds the _id and text given the text as input, for example, for the keyword "bar1" the output would be something like this:</p>
  
  <pre><code>{ 
  "_id" : 2.0, 
  "text": "bar1"
  }
  </code></pre>
  
  <p>I can achieve this if the text that I am looking for is in a single array at the top level of the document, but I cannot do it with an array inside another array.</p>
  
  <p>So far my query looks like this:</p>
  
  <pre><code>db.collection.aggregate([{$match:{"pages.texts.text":"bar1"}},
                  { $project:
                      { text: 
                          { $filter: 
                              { input: '$pages.texts.text', 
                                as: 'text', 
                                cond: { $eq: [ "$$text" , "bar1"]}
                              }
                          },
                        _id:1
                      }
                  }
                  ])
  </code></pre>
  
  <p>Which gives as output this:</p>
  
  <pre><code>{ 
  "_id" : 2.0, 
  "text" : [
  
  ]
  }
  </code></pre>
  
  <p>It shows the correct _id but no text.</p>
  
  <p>If I change the operator $eq for $ne in the filter the output is:</p>
  
  <pre><code>{ 
  "_id" : 2.0, 
  "text" : [
      [
          "bar", 
          "bar1", 
          "bar2"
      ]
  ]
  }
  </code></pre>
  
  <p>It seems that text is an array of arrays and I cannot compare directly the keyword with this field. I have tried different approaches to solve this but no luck so far.</p>
  
  <p>Any help would be greatly appreciated.</p>
  
  <p>Thank you!</p>