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

269
Views
Mongo aggregation: add field derived from another field

I have documents of the following form present in a collection:

{
  name: "Michael",
  likes: [{ name: "reading", amount: 80}, {name: "eating", amount: 70}]
}

I want to add a new field to all the documents which will be 0/1 depending on whether the person likes reading. I have to check for the presence of likes.name = "reading". I tried adding the following stage in my aggregation pipeline to achieve this:

$addFields: {
  likes_reading: {
    $cond: {
      if: {
        $eq: ["$likes.name", "reading"]
      },
      then: 1,
      else: 0
    }
  }
}

However, $eq doesn't seem to be checking if "any" element of likes array has the required name, which is the kind of behaviour I've seen in many other places when we compare values with arrays. As a result all the likes_reading are set to 0. I need help setting this new field properly.

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

Since likes is an array you have to use $in operator so try this:

{
    $addFields: {
        likes_reading: {
            $cond: {
                if: { $in: ["reading", "$likes.name"] },
                then: 1,
                else: 0
            }
        }
    }
}

Or

{
    $addFields: {
        likes_reading: {
            $cond: [{ $in: ["reading", "$likes.name"] }, 1, 0]
        }
    }
}
over 4 years ago · Santiago Trujillo Report
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!