nrion
nrion

Reputation: 4994

Query an object array to check if it contains an array of strings in mongoose

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!

Upvotes: 2

Views: 1550

Answers (1)

Ashh
Ashh

Reputation: 46451

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

Upvotes: 3

Related Questions