Jiaming Lin
Jiaming Lin

Reputation: 57

How to remove an nested array element from Array

I want to remove an nested array element if its first value is 0 from array. The data is shown below.

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

test case

And here is my solution, which doesn't work.

db.collection.update({},
{
  "$pull": {
    "data": {
      "$elemMatch": {
        "0": 0
      }
    }
  }
})

Upvotes: 2

Views: 82

Answers (1)

Tom Slabbaert
Tom Slabbaert

Reputation: 22296

If you're using Mongo version 4.2+ you can use pipelined updates like so:

db.collection.update({},
[
  {
    $set: {
      data: {
        $filter: {
          input: "$data",
          as: "datum",
          cond: {
            $ne: [
              {
                $arrayElemAt: [
                  "$$datum",
                  0
                ]
              },
              0
            ]
          }
        }
      }
    }
  }
])

Mongo Playground

Upvotes: 4

Related Questions