How to get array elements using a list of index in mongoDB?

Viewed 138

Consider the following document in mongoDB:

{words:['a','b','c','d','e','f']}

I know it's easy to get a single element or a range in mongodb using $arrayElemAt or $slice.

But how can I get multiple elements by giving a list of indices?

For example, if I have a list of indices:

[0,2,5]

the expected result is:

{words:['a','c','f']}
1 Answers

You can pass your array as in parameter into $map and then use $arrayElemAt operator:

db.collection.aggregate([
    {
        $project: {
            words: {
                $map: {
                    input: [0,2,5],
                    as: "index",
                    in: { $arrayElemAt: [ "$words", "$$index" ] }
                }
            }
        }
    }
])

Mongo Playground

Related