Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

358
Views
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
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!