2

Supposing I have the following array:

{
   data: [1, 0, 4, 0, 0, 4, 1, 3, 0, 1, 0, 2, 2, 0, 1, 1, 0, 2, 0, 4, 1, 1, 0, 1, 1, 0]
}

if I want to select all the elements, except the last 3, I can use the solution proposed here

db.collection.aggregate([
  {
    $project: {
      "_id": 0,
      "data": {
        "$slice": [ 
          "$data",
          0,
          {
            $subtract: [ { $size: "$data" }, 3 ]
          }
        ]
      }
    }
  }
])

I can get the desired output:

[1, 0, 4, 0, 0, 4, 1, 3, 0, 1, 0, 2, 2, 0, 1, 1, 0, 2, 0, 4, 1, 1, 0]

How can I do the same thing for concatenated/nested arrays like:

 {
       data: [[1, 0, 4, 0, 0, 4, 1], [1, 0, 4, 0, 1, 5, 3]]
 }

In order to select all the elements, except the last 3 (of each array)?

Expected output:

        {
           data: [[1, 0, 4, 0], [1, 0, 4, 0]]
        }

1 Answer 1

3

You can use $map to iterate over array's & do the same :

db.collection.aggregate([
  {
    $addFields: {
      data: {
        $map: {
          input: "$data",
          in: {
            "$slice": [
              "$$this",
              0,
              {
                $subtract: [
                  {
                    $size: "$$this"
                  },
                  3
                ]
              }
            ]
          }
        }
      }
    }
  }
])

Test : MongoDB-Playground

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

1 Comment

Thank you very much

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.