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

122
Views
MongDB Aggregate two values with same name

i have the following aggregate function in my code to count how many times a value is found in the db:

  let data: any = await this.dataModel.aggregate(
      [
        {
          $match: {
            field: new ObjectID(fieldID),
          },
        },
        {
          $group: {
            _id: "$value",
            total_for_value: { $sum: 1 },
          },
        },
      ]
    );

This works correctly, however my data setup is a bit different. I have two types of value fields. Some like this:

    {
    "_id" : ObjectId("123"),
    "value" : "MALE"
    }

and some like this:

{
    "_id" : ObjectId("456"),
    "value" : {
        "value" : "MALE",
    }
}

Is there a way to group the ones where the _id and the _id.value are the same? At the moment it counts them separately.

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

0

db.collection.aggregate([
  {
    "$addFields": {
      "key2": {
        "$cond": {
          "if": {
            $and: [
              {
                "$eq": [
                  {
                    "$type": "$key"
                  },
                  "object"
                ]
              }
            ]
          },
          "then": "$key.value",
          "else": "$key"
        }
      }
    }
  },
  {
    "$group": {
      "_id": "$key2",
      "data": {
        $push: "$$ROOT"
      }
    }
  }
])

This would do the job if _id.value is an object.

Playground

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!