0

I try to match a document in this nested structure, it works for one level but not for the second level:

{
 type:"example"
 level1:[
          {
            name:"Bill"
            level2:[
                     {
                       skill:"gardening"
                     },
                     {
                       skill:"carpentry"
                     }
            ]

           },

          {
            name:"John"
            level2:[
                     {
                       skill:"painting"
                     },
                     {
                       skill:"acrobatics"
                     }
            ]

          }
        ]

}

I can match the first level array, for example:

db.collection.find({"level1.name":{$eq:"Bill"}})

But if for example I want to math the document with the skill field equal to "acrobatics" I do:

db.collection.find({"level1.level2.skill":{$eq:"acrobatics"}})

Does not work, any idea? (sorry if the naming of the example does not make much sense, but that's the structure that I'm facing).

Thank you!

9
  • 1
    it is working mongoplayground.net/p/goQq_Hs55Z2 Commented Aug 13, 2020 at 9:39
  • 1
    exactly what was your question? query is not working or you need whole structure in result? you can update your question first. Commented Aug 13, 2020 at 9:57
  • 1
    It's returning the whole structure because the collection only has 1 document, which matches the query. Commented Aug 13, 2020 at 9:57
  • 2
    @Mapin you can project in find using $ check this mongoplayground.net/p/1hl2l3CGKPb Commented Aug 13, 2020 at 10:03
  • 1
    @varman yes you are right, this is helpful only in unique value, and for multiple match there is a only option is aggregation. Commented Aug 13, 2020 at 10:22

1 Answer 1

1

There are multiple ways you can do this. You can try something like this.

  1. $unwind to flatten the first level array
  2. $match to match the element that you need
  3. $group to group back to the same level

Shell query is given below

[
  {
    "$unwind": "$level1"
  },
  {
    $match: {
      "level1.level2.skill": "acrobatics"
    }
  },
  {
    "$group": {
      _id: "$_id",
      level1: {
        "$addToSet": "$level1"
      }
    }
  }
]

Working Mongo playground

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks, I'll have to do pipelines for fast classification as well:)
So you can easily do with $match stage.
@varman you can use $push instead of $addToSet, because $addToSet will replace the same object, look mongoplayground.net/p/NKMZOvnrYlv

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.