2

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 Answer 1

1

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

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

Comments

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.