Tobias Reich
Tobias Reich

Reputation: 2034

Combine multiple projections in MongoDB aggregation

My MongoDB (v4.2) pipeline consists of multiple projections to subtract, divide, ceil and multiply a value.

Is there a way to combine them without using multiple projections?

My pipeline:

[
    {
        $project: {
            duration: {
                $subtract: [ '$updated', '$created' ]
            }
        }
    },
    {
        $project: {
            duration: {
                $divide: [ '$duration', precision ]
            }
        }
    },
    {
        $project: {
            duration: {
                $ceil: [ '$duration' ]
            }
        }
    },
    {
        $project: {
            duration: {
                $multiply: [ '$duration', precision ]
            }
        }
    },
    {
        $group: {
            _id: '$duration',
            count: {
                $sum: 1
            }
        }
    }
]

Example data:

[
    { created: 1569763367, updated: 1569773367 },
    { created: 1569760000, updated: 1569770000 },
    { created: 1569772415, updated: 1569773519 },
]

Upvotes: 0

Views: 479

Answers (1)

Tobias Reich
Tobias Reich

Reputation: 2034

It's seems to be possible, but it's not very readable:

[
    {
        $project: {
            duration: {
                $multiply: [
                    {
                        $ceil: [
                            {
                                $divide: [
                                    {
                                        $subtract: [ '$updated', '$created' ]
                                    },
                                    precision
                                ]
                            }
                        ]
                    },
                    precision
                ]
            }
        }
    },
    {
        $group: {
            _id: '$duration',
            count: {
                $sum: 1
            }
        }
    }
]

Upvotes: 1

Related Questions