Aggregate function – using $project and $group

If you want the aggregated data to be stored in a specific column format then use $project.

Here is an example:-

pipeline1 = [
                    {
                        '$group':
                            {'_id': {
                                'device_id': '$device_id',
                                'date': {'$dateToString': {'format': '%Y-%m-%d', 'date': '$timestamp'}},
                            },
                                'avg_v': {'$avg': "$value"},
                                'min_v':{'$min':"$value"},
                                'max_v':{'$max':"$value"}
                            }

                    },
                    {
                        '$project':
                            {
                                '_id': 0,
                                'device_id': '$_id.device_id',
                                'avg_value': '$avg_v',
                                'min_value': '$min_v',
                                'max_value': '$max_v',
                                'date': '$_id.date'
                            }
                    }
                 ]

The aggregated data structure will be as shown below in database:-

_id: 61af14c283751487558e8494
device_id: "DT002"
avg_value: 23
min_value: 19
max_value: 26
date: "2020-12-05"

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: