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

171
Views
How to compare string feild value in aggregation mongodb

in the following image i am using $project aggregation. i need to compare whether text feild is equals to 'A' or not using $cond. If this boolean condition is true it should return 1 otherwise 0. but it is showing Stage must be properly formatted.

{
  'answers.Urban_City.text': 1,
  SEC_A: {$cond:['answers.SEC.text':['$eq','A'], 1,  0]}
}

compass image link

Sample document i have multiple documents like this

{
  "_id": {
    "$oid": "61dea2c1169cd059e2d1a06e"
  },
  "metaKey": {
    "projectId": 7,
    "sectionId": 5,
    "userId": 5,
    "simpleSurveyResponseCode": "58836213476714"
  },
  "answers": [
    {
      "Urban_City": {
        "text": "Karachi",
        "value": "72"
      }
    },
    {
      "SEC": {
        "text": "A",
        "value": "1"
      }
    }
  ],
  "__v": 0
}

I want something like this

db.Sentiments.aggregate(
    { $project: {
        _id: 0,
        Company: 1,
        PosSentiment: {$cond: [{$gt: ['$Sentiment', 0]}, '$Sentiment', 0]},
        NegSentiment: {$cond: [{$lt: ['$Sentiment', 0]}, '$Sentiment', 0]}
    }},
    { $group: {
        _id: "$Company",
        SumPosSentiment: {$sum: '$PosSentiment'},
        SumNegSentiment: {$sum: '$NegSentiment'}
    }});

but at the place of Sentiment i have SEC which is embedded array contains two feilds(String) mentioned in sample document. where i have stuck in $project aggregation if this gets resolved $group would be easy for me.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Try this one:

db.collection.aggregate([
   {
      $project: {
         'answers.Urban_City.text': 1,
         SEC_A: {
            $map: {
               input: "$answers",
               in: { $cond: [{ $eq: ['$$this.SEC.text', 'A'] }, 1, 0] }
            }
         }
      }
   }
])

If you provide a desired sample output, the change will be much higher to receive an appropriate answer.

about 4 years ago · Juan Pablo Isaza 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!