Mongodb update array in array

Viewed 52

I want to update this document:

  {
    "user_id": "60800ba9a9ccaf160e385612",
    "date": "2021-03-20",
    "data": [
      [
        {
          "type": "blind_mouse",
          "count": 1,
          "played_count": 0
        },
        {
          "type": "color_and_shape_matching",
          "count": 1,
          "played_count": 0
        }
      ],
      [
        {
          "type": "thieves_and_police",
          "count": 3,
          "played_count": 0
        },
        {
          "type": "boat",
          "count": 3,
          "played_count": 0
        }
      ]
    ]
  }

Actually, update played_count where type equal by "blind_mouse".

I tried this query but it won't work:

$collection_games_delivered->updateOne(
    ['user_id' => $_SERVER['HTTP_USERID'], 'date' => $date, 'data.$.type' => $type],
    [
        '$set' => ['data.$.played_count' => $played_count]
    ]
);

How I can fix this?

1 Answers
  • update part, $[] for first level array and $ for positional matching type
  • use arrayFilters to update positional element, search for type
db.collection.updateOne(
  {
    user_id: "60800ba9a9ccaf160e385612",
    date: "2021-03-20"
  },
  { $set: { "data.$[].$[e].played_count": 1 } },
  {
    arrayFilters: [
      { "e.type": "thieves_and_police" }
    ]
  }
)

Playground

PHP syntax:

$collection_games_delivered->updateOne(
  [
    'user_id' => $_SERVER['HTTP_USERID'], 
    'date' => $date
  ],
  [
    '$set' => ['data.$[].$[e].played_count' => $played_count]
  ],
  [
    'arrayFilters' => [
      'e.type' => 'thieves_and_police'
    ]
  ]
);
Related