1

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.

1 Answer 1

3

You can simply use $all

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

Working Mongo playground

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

2 Comments

Thanks for this! Perfect. How about if it's nested within an object? I can't seem to get it working: Mongo Playground
In that case, you need to go with aggregations

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.