2

I have the following query.

   db.Collection.aggregate([
  {
        "$match":{
            "index": 1
                 }
  },

  {
        "$addFields":{
            "DATE": $var1
            "array":"$array1
                     }
  }

])

This is the result of the query.

OUTPUT1

    {
        "DATE" : 181019
        "array" : 100,101,105,106,201,205,208,209
    }
...
...

and I'm going to get a $group results. I will use $array1.

    db.Collection.aggregate([
  {

        {
         $group:{
             "_id":"$array1",
             "count":{"$sum" : 1}
                }
        },

        {
        $sort: {"count" : -1}

        }


  }
])

OUTPUT2

{
 "_id" : [
100,
101,
105,
106,
201,
205,
208,
209],

"count" : 4.0

}

"count" results will copy on all results.

But $group will make a bad structure to read all data.

How do I merge ALL OUTPUT1 with $group "count" of OUTPUT2?

     {
            "$addFields":{
                "DATE": $var1
                "array":"$array1
                "count": $count
                         }
      }

Using $group "count", but I don't want $group structure.

   {
        "DATE" : 181019
        "array" : 100,101,105,106,201,205,208,209
        "count" : 4.0
    },
    {
        "DATE" : 181019
        "array" : 103,104,105,106,201,205,208,210
        "count" : 12.0
     }
...
...
s7vr
  • 73,656
  • 11
  • 106
  • 127
Spark_Py
  • 21
  • 5

1 Answers1

0

mongo group query how to keep fields

I found what I want. The answer is $group trick.

first, Shifts $addfield's query to $group{query}.

Secondly, add {$first:{}} to $addfield's query That makes $addfield's query $group query.

$group:{
_id: $group_var,
name:{$first:{$addfield's query}}
"count": $count
}

This is the result of putting it in.

 db.Collection.aggregate([
  {

        {
         $group:{
             "_id":"$array1",
             "array":{"$first":"$array1}
             "count":{"$sum" : 1}
                }
        },

        {
        $sort: {"count" : -1}

        }


  }
])
Spark_Py
  • 21
  • 5