Search code examples
javascriptmongodbaggregate

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.


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