bourkison
bourkison

Reputation: 101

Return document where array element includes all values of input array | MongoDB

I have a collection of exercises:

[
    {
        "name": "Push Ups",
        "muscleGroups": ["Chest", "Shoulders", "Abs", "Biceps"]
    },
    {
        "name": "Sit Ups",
        "muscleGroups": ["Abs"]
    },
    {
        "name": "Pull Ups",
        "muscleGroups": ["Abs", "Biceps", "Back"]
    }
]

and an input array of inputMuscleGroups. I am trying to filter the exercises to where the muscleGroups array of the document has every element of the inputMuscleGroups.

For inputMuscleGroups = ["Abs"], every document would return.

For inputMuscleGroups = ["Abs", "Biceps"], output would be:

[
    {
        "name": "Push Ups",
        "muscleGroups": ["Chest", "Shoulders", "Abs", "Biceps"]
    },
    {
        "name": "Pull Ups",
        "muscleGroups": ["Abs", "Biceps", "Back"]
    }
]

For inputMuscleGroups = ["Abs", "Shoulders", "Chest"], output would be:

[
    {
        "name": "Push Ups",
        "muscleGroups": ["Chest", "Shoulders", "Abs", "Biceps"]
    }
]

I have played around with $in but it appears these only return true if any of the input arrays match any of the document array.

Ideally I would want to do this within a .find() method as opposed to a .aggregate() method.

Upvotes: 1

Views: 534

Answers (1)

varman
varman

Reputation: 8894

You can simply use $all

db.collection.find({
  muscleGroups: {
    $all: [
      "Abs",
      "Biceps"
    ]
  }
})

Working Mongo playground

Upvotes: 3

Related Questions