Getting the count of nested array field in Mongo DB

Hi,
given below is my document structure after a $lookup stage.

doc1:

{
“_id”: {
“$oid”: “63be50667a6c91dc6bf00e97”
},
“textId”: “29563”,

"textValuesTr": [
  {
    "_id": {
      "$oid": "63be50667a6c91dc6bf00e97"
    },
    "textId": "29563",
    "localeCode": "en-ZZ",
    "textValues": [
      {
        "textPart": "PTYPE-001",
        "status": "source"
      },
      {
        "textPart": "PTYPE-002",
        "status": "source"
      },
      {
        "textPart": "PTYPE-003",
        "status": "source"
      },
      {
        "textPart": "PTYPE-004",
        "status": "source"
      }
    ]
  },
  {
    "_id": {
      "$oid": "63be54a6dc5b5823d4b2458b"
    },
    "textId": "29563",
    "localeCode": "es-ES",
    "textValues": [
      {
        "textPart": "PTYPE-001",
        "status": "Translated"
      },
      {
        "textPart": "PTYPE-002",
        "status": "Translated"
      },
      {
        "textPart": "PTYPE-003",
        "status": "Translated"
      },
      {
        "textPart": "PTYPE-004",
        "status": "Translated"

      }
    ]
  }
]

}

doc2:

{
“_id”: {
“$oid”: “63be506d7a6c91dc6bf072fe”
},
“textId”: “0049912”,
“textValuesTr”: [
{
“_id”: {
“$oid”: “63be506d7a6c91dc6bf072fe”
},
“textId”: “0049912”,
“localeCode”: “en-ZZ”,
“textValues”: [
{
“status”: “source”
}
]
},
{
“_id”: {
“$oid”: “63be54badc5b5823d4b2a564”
},

    "textId": "0049912",
    "localeCode": "es-ES",
    "textValues": [
      {
        "status": "Translated"
      }
    ]
  }
]

}

I want to calculate the count of translated documents and count of user
I tried using $group aggregation inside &facet but it is not giving the expected output.

aggregation tried for status count is

{

$facet:{
status_cnt: [
{
$group: {
_id: {
$let: {
vars: {
item: {
$arrayElemAt: [
“$textValuesTr.textValues”,
1,
],
},
},
in: “$$item.status”,
},
},
count1: {
$sum: 1,
},
},
},
],
}
}

It is giving the Output as:-
[{
“status_cnt”: [

{
  "_id": [
    "Translated"
  ],
  "count1": 1
},
{
  "_id": [
    "Translated",
    "Translated",
    "Translated",
    "Translated"
  ],
  "count1": 1
}

]
}]

But I want the output in the below format

[{
“status_cnt”: [
{
“_id”: [
“Translated”
],
“count1”: 2
},
]
}]

Please help me.

Regards,
Vishnupriya.

Thank God! I got a solution that best matches my requirement.

I just used two $project stages to manipulate the nested array field using $arrayElemAt before $facet stage. Currently it is working fine for me.

Thank you.

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.