Using $group to count all documents in the collection and getting back all entire documents by fieldName

Hello everyone,
I have a dataset like below:
{ “_id” :{ “time” : “01:00”}, “subDocument” : { “field1” : 42, “field2” : 10, “field3” : “yes” } }
{ “_id” :{ “time” : “01:01”}, “subDocument” : { “field1” : 14, “field2” : 6, “field3” : “yes”} }
{ “_id” :{ “time” : “01:02”}, “subDocument” : { “field1” : 6, “field2” : 11, “field3” : “yes” } }
{ “_id” :{ “time” : “01:03”}, “subDocument” : { “field1” : 3, “field2” : 26, “field3” : “no” } }

I want to count the the number of field3:"yes", but also want to show all entire fields.

 Result would look like below:
{
  "_id" : "yes",
  "agree" :
     [
       { "_id" :{ "time" : "01:00"}, "subDocument" : { "field1" : 42, "field2" : 10, "field3" : "yes"  }  }
       { "_id" :{ "time" : "01:01"}, "subDocument" : { "field1" : 14, "field2" : 6, "field3" : "yes"}  }
       { "_id" :{ "time" : "01:02"}, "subDocument" : { "field1" : 6, "field2" : 11, "field3" : "yes" }  }
     ],
   "totalYes" : 3
}

I tried to follow the example
https://docs.mongodb.com/manual/reference/operator/aggregation/group/#std-label-null-example
but I got an error.
How can I count the subDocument?

Many thanks
1 Like

It would help if you share the error you got and the exact query you tried. Most likely you have some cut-n-paste or syntax error. Without the exact query and without the exact error message there is nothing we can do except sending you to the same documentation you shared.

Hello Steeve, thanks for your reply. Here is the photo shows the original data.
image

I actually want to get the data length of all documents. In this case, would be 52.
I want to use this value for the for loop afterward.

here is my exact code:
// i create NoOfDoc and DLength just for counting the total no. of documents.
{
“$addFields”: { signals: { “NoOfDoc”:1} }
},

{
“$addFields”: { signals: { “DLength”:“length”} }
},

{
$group : {

  "signals" : { "DLength" : "length", iloop: {"$push": "$ROOT"}}

},
{
“$addFields”: { signals: { totalNoOfDoc: {"$sum":"$iloop.NoOfDoc"} }
}

the error message is:

Looks like you are missing a closing brace in the above