Uploaded image for project: 'Core Server'
  1. Core Server
  2. SERVER-77974

$all operator does not work on on $elemMatch

    • Type: Icon: Bug Bug
    • Resolution: Done
    • Priority: Icon: Major - P3 Major - P3
    • None
    • Affects Version/s: None
    • Component/s: None
    • Labels:
      None
    • Server Triage
    • ALL

      Hello, 

      I am very new to mongo, so please forgive me if I am misusing the query syntax, but I have this situation that is either a bug or somebody please tell me how to correctly do it instead. Thank you.

      I am trying to find documents where any or all nested array elements must contain at least the values provided. This can normally be achieved easily with the $all operator. For example here:

      [
        {
          "words": [ "Hello", "World", "!"],
          "wordArrays": [
            ["Hello", "World", "!"],
            ["The", "Sun", "Shines"]
          ]
        }
      ] 

      The query 

      {words: {$all: ["Hello", "World"]}}

       correctly matches because both are contained and 

      {words: {$all: ["Hello", "I do not exist"]}} 

       does not match. So far so good.

       

      If you attempt the same for the nested arrays this stops working altogether. 

      {"wordArrays.0": {$all: ["Hello", "World"]}} 

      The above does not match. I have found Stackoverflow questions about why on nested arrays all the operators start to fail but no one ever can explain why and they just use $elemMatch. But I do not know how I would translate my "all values must be in the array" to an $elemMatch. How I would say

      1. ANY of the wordArrays must contain "Hello" and "World" -> would match
      2. ALL of the wordArrays must contain "Hello" and "World" -> would not match the data

      I have prepared this little playground with the data in the hopes somebody knows how to achieve this.
      https://mongoplayground.net/p/WSM2OGh-5vk

      I would prefer if this could be solved all within the Find() stage, but if operations like this suddenly require the aggregation pipeline I am fine with that too.

      My approach for ANY match does not return any matches, and I do not understand why 

      {wordArrays: {$elemMatch: {$all: ["Hello", "World"]}}} 

      I read it as wordArrays: does any element match: array contains "Hello" and "World". And that should have matched the document

      Thank you!

            Assignee:
            backlog-server-triage [HELP ONLY] Backlog - Triage Team
            Reporter:
            arkensor@gmail.com Arkensor N/A
            Votes:
            0 Vote for this issue
            Watchers:
            5 Start watching this issue

              Created:
              Updated:
              Resolved: