2

say i have the following inside my db:

knights
  {
    name: 'Knightley',
    skills: [
      { name: 'sword', level: 2 },
      { name: 'shield', level: 1 }
    ]
  },
  {
    name: 'Cowardly',
    skills: [
      { name: 'sword', level: 1 },
      { name: 'shield', level: 5 }
    ]
  }

and i want to return all knights with skills of sword and shield. something like this (pseudo):

Knight.find({ skills.name: which contains ['sword', 'shield'] })

how do i do this kind of query? thanks!

2
  • You want to test both sword and shield is in array? Commented Jun 21, 2018 at 12:42
  • the above pseudo code would return both knights, as it contains both skills with sword and shield Commented Jun 21, 2018 at 12:45

1 Answer 1

3

You need to use $elemMatch to find inside the array with $in operator

db.collection.find({
  skills: {
    $elemMatch: {
      name: { $in: ["sword", "shield"] }
    }
  }
})

Output

[
  {
    "name": "Knightley",
    "skills": [
      {
        "level": 2,
        "name": "sword"
      },
      {
        "level": 1,
        "name": "shield"
      }
    ]
  },
  {
    "name": "Cowardly",
    "skills": [
      {
        "level": 1,
        "name": "sword"
      },
      {
        "level": 5,
        "name": "shield"
      }
    ]
  }
]

Check it here

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

Comments

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.