arlugones
arlugones

Reputation: 113

How to extract a slice of an array given an element position in MongoDB?

I'm trying to extract a slice of an array in MongoDB given the position of a certain element (action4 in the example). The sample data is

[{name: 'John Doe', actions: ['action1', 'action2', 'action3', 'action4']},
{name: 'Margie Addams', actions: ['action1', 'action2', 'action4', 'action3']},
{name: 'Fer Doughnut', actions: ['action1', 'action4', 'action3', 'action2']},
{name: 'Anthony Peralta', actions: ['action1', 'action2', 'action3', 'action4']},
{name: 'Pete Parker', actions: ['action1', 'action2', 'action3', 'action4']},
{name: 'Josh Dean', actions: ['action4', 'action2', 'action3', 'action1']}]

I managed to find the position of action4 inside the array with an aggregation query like

{$indexOfArray: ["$actions", "action4"]}

but can't find a way to extract from the beginning of the array to its position. Any suggestion?

Upvotes: 0

Views: 124

Answers (1)

SuleymanSah
SuleymanSah

Reputation: 17858

You can use $slice and $indexOfArray aggregation operators like this:

db.collection.aggregate([
  {
    $addFields: {
      actions: {
        $slice: [
          "$actions",
          {
            $indexOfArray: [
              "$actions",
              "action4"
            ]
          }
        ]
      }
    }
  }
])

Playground

Upvotes: 1

Related Questions