Friday, 5 August 2016

mongodb count and sum array size after a group/aggregation

Above is a very common mongo aggregate, you may have the same issue when you first time use this.

it is looks like, you can only group fields by $sum, but how to keep values of other fields?

The answer is: you can not keep them.

What? i can not ? but how can i do other operations after the group?

there are two ways, you can keep them by some degree:

Usually I do like this to keep values:

Of cause this only works if this field have the same value after grouped.

If the field have different value after grouped, you can put all of them into an array first (i will talk about how to use these data later):

In above picture, i am grouping data by storeID, messages are not different in even same stores. The type messages is array. So i put messages into a new array.

To get them, you need to do "$unwind"

"$unwind" will split array into rows, like de-grouping.

As you can see above, i de-grouped twice because when i put messages into a new array, they are array, which means the new array is a 2-d array, that is why i de-grouped twice.

After that, i then regroup them again, then i can get all messages size which is grouped by store.

No comments:

Post a comment