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

363
Vistas
How to use $cond to push into a field in mongodb findOneAndUpdate?

I have a schema like this

{
  _id: ObjectId('xyz'),
  project_type: 'A', // enum ['A', 'B']
  status: 'Working', // enum ['Pending', 'Working', 'Completed']
  userId: ObjectId('abc'),
  work_start: [{ userId: ObjectId('pqr'), timestamp: Date() }],
  work_submitted: [{ userId: ObjectId('pqr'), timestamp: Date() }]
}

I want to fetch the document based on the following condition

  • If the status is 'Pending'
  • If the status is 'Working' and userId=given userId

and while fetching I also want to update the work_start array with a new object

  1. If status was 'Pending' add new {userId: ObjectId, timestamp: Date()} to work_start array
  2. If status was 'Working' and userId = given userId, don't add new object to work_start array

Here is the query I have written but I am not able to fulfill the 2nd condition

 collection.findOneAndUpdate(
                {
                    project_type: 'A',
                    $or: [
                        { status: 'Pending' },
                        {
                            $and: [
                                { status: 'Working' },
                                { userId: userId }
                            ]
                        }
                    ]
                },
                {
                    $push: { work_start: { userId, timestamp: new Date() } }, // Here I want to use the conditional block
                    $set: {
                        status: 'Working',
                        userId: userId
                    }
                },
                {
                    sort: { "created_on": 1 },
                    returnDocument: 'after' // return updated document
                },
            );

How can I do something like this?

$cond: { 
   if : { status: 'Working' and {userId: userId}}, 
   then: // do nothing 
   else: { $push: { work_start: { userId, timestamp: new Date() }  } } },    } 
about 4 years ago · Juan Pablo Isaza
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