0

I have an orders table and a forms table. forms has many orders and i ran a successful $lookup with the following:

{
    from: 'orders',
    localField: 'slug',
    foreignField: 'form_slug',
    as: 'orders'
}

I then try to project like this:

{quantities : "$orders.line_items.quantity"}

The issue is that i get an array of nested arrays (see result below), when i really just want a sum total.

Is is possible to somehow $sum these values within the nested array?

"quantities": [
    [
        NumberLong(1)
    ],
    [
        NumberLong(1),
        NumberLong(1)
    ],
    [
        NumberLong(1)
    ],
    [
        NumberLong(1)
    ],
    [
        NumberLong(1)
    ],
    [
        NumberLong(1),
        NumberLong(1),
        NumberLong(1)
    ],
    [
        NumberLong(1)
    ],
    [
        NumberLong(1)
    ]
]
0

2 Answers 2

1

Query

    {
        "$lookup": {
            "from": "orders",
            "localField": "slug",
            "foreignField": "form_slug",
            "as": "orders"
        }
    }, {
        "$unwind": "$orders"
    }, {
        "$unwind": "$orders.line_items.quantities"
    }, {
        "$unwind": "$orders.line_items.quantities"
    }, {
        "$group": {
            "_id": "$_id",
            "sum": {
                "$sum": "$orders.line_items.quantities"
            }
        }
    }

Sign up to request clarification or add additional context in comments.

1 Comment

since i'm using the 3.2 version this works, although i think there is a typo in the second unwind. shouldn't that be "$unwind": "$orders.line_items"?
1

You can try aggregation for Mongo 3.4 version

The below query uses $reduce with $concatArrays to reduce to array of values chaining with another $reduce to calculate the total.

{
 $project: {
        total: {
            $reduce: {
                input: {
                    $reduce: {
                        input: "$orders.line_items.quantity",
                        initialValue: [],
                        in: {
                            $concatArrays: ["$$value", "$$this"]
                        }
                    }
                },
                initialValue: 0,
                in: {
                    $add: ["$$value", "$$this"]
                }
            }
        }
    }
}

Mongo 3.2 and lower. Add the below stages after $lookup

{$unwind:"$orders"},
{$unwind:"$orders.line_items"},
{$unwind:"$orders.line_items.quantity"},
{$group:{"_id":null, total:{"$sum":"$orders.line_items.quantity"}}}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.