Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

362
Visualizações
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 à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda