Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

73
Vistas
MongoDB update value of deeply nested array and sort

I have this document of timestamps sorted by time:

{
  _id: '1',
  timestamps: [
    {
      id: '589b32cf-28b3-4a25-8fd1-5e4f86682199',
      time: '2022-04-13T19:00:00.122Z'
    },
    {
      id: '781a47de-d21a-4c2c-9814-b46f4a3cfa30',
      time: '2022-04-13T20:00:00.498Z'
    }
  ]
};

I want to update a timestamp by id, change the time, and sort

example: update timestamp with id: '589b32cf-28b3-4a25-8fd1-5e4f86682199':

{
  id: '589b32cf-28b3-4a25-8fd1-5e4f86682199',
  time: '2022-04-13T20:30:00.122Z'
}

the updated document should like this:

{
  _id: '1',
  timestamps: [
    {
      id: '32bb3-2222-1111-j878-b4000a3wwa30',
      time: '2022-04-13T19:30:00.122Z'
    },
    {
      id: '589b32cf-28b3-4a25-8fd1-5e4f86682199',
      time: '2022-04-13T20:30:00.122Z'
    }
  ]
};

I came up with this method to update and sort each element in the array:

const updateResult = await TimestampCollection.updateOne(
  { _id: '1' },
  {
    $push: {
      timestamps: {
        $each: [{ id: timestamp.id, time: timestamp.time }],
        $sort: { time: 1 }
      }
    }
  }
);

However this pushed a new object to the array with the same id and updated time:

{
  _id: '1',
  timestamps: [
    {
      id: '589b32cf-28b3-4a25-8fd1-5e4f86682199',
      time: '2022-04-13T19:00:00.122Z'
    },
    {
      id: '32bb3-2222-1111-j878-b4000a3wwa30',
      time: '2022-04-13T19:30:00.122Z'
    },
    {
      id: '589b32cf-28b3-4a25-8fd1-5e4f86682199',
      time: '2022-04-13T20:30:00.122Z'
    }
  ]
};

Any idea how to fix this?

over 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

I didn't find a way to do this in a single query. Sadly combining $set and $push in a single query leads to a conflict...

db.collection.update({
  _id: "1",
  "timestamps.id": timestamp.id
},
{
  "$set": {
    "timestamps.$.time": timestamp.time
  },
});

db.collection.update({
  _id: "1",
},
{
  "$push": {
    "timestamps": {
      "$each": [],
      "$sort": {
        "time": 1
      }
    }
  }
})

This solution involves two queries. One for updating the element in the array and the other for sorting the array.

over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda