1

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.

Submitted July 26th 2021 by Admin

Answers
0

You can simply use $all

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

Working Mongo playground

Admin | 1 month ago



Relevant Questions




Deleting a todo - MERN Stack

September 10th 2021