sql >> Base de Datos >  >> NoSQL >> MongoDB

Actualización de un registro anidado en la matriz mongodb cuando no conoce el índice del documento

DEMOSTRACIÓN :Zona de juegos MongoDB

En primer lugar, hay errores en su JSON.

JSON

[
  {
    "_id": "60753fd9b249ad0dfa1eeb48",
    "name": "Random Name 1",
    "email": "[email protected]",
    "likings": [
      {
        "breakfast": {
          "eat": "oats",
          "drink": "milk"
        }
      },
      {
        "lunch": {
          "eat": "beef",
          "drink": "pepsi"
        }
      },
      {
        "dinner": {
          "eat": "steak",
          "drink": "champagne"
        }
      }
    ]
  },
  {
    "_id": "60753fd9b249ad0dfa1eeb58",
    "name": "Random Name 2",
    "email": "[email protected]",
    "likings": [
      {
        "breakfast": {
          "eat": "cereals",
          "drink": "coffee"
        }
      },
      {
        "lunch": {
          "eat": "salad",
          "drink": "hot-water"
        }
      },
      {
        "dinner": {
          "eat": "biryani",
          "drink": "apple juice"
        }
      }
    ]
  }
]

Prueba esto:

db.collection.update({
  "name": "Random Name 2",
  "likings.dinner": {
    "$exists": true
  }
},
{
  "$set": {
    "likings.$.dinner.drink": "PEPSI"
  }
})

Puedes cambiar dinner a cualquier campo que desee actualizar en consecuencia.