Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

{
    "_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.

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading