0

I'm trying to return size of 'orders' and sum of 'item' values for each 'order' for each order from documents like the example document:

    orders: [
    {
        order_id: 1,
        items: [
            {
                item_id: 1,
                value:100
            },
            {
                item_id: 2,
                value:200
            }
        ]
    },
    {
        order_id: 2,
        items: [
            {
                item_id: 3,
                value:300
            },
            {
                item_id: 4,
                value:400
            }
        ]
    }
]

I'm using following aggregation to return them, everything works fine except I can't get size of 'orders' array because after unwind, 'orders' array is turned into an object and I can't call $size on it since it is an object now.

db.users.aggregate([
{
    $unwind: "$orders"
},
{
    $project: {
        _id: 0,
        total_values: {
            $reduce: {
                input: "$orders.items",
                initialValue: 0,
                in: { $add: ["$$value", "$$this.value"] }
            }
        },
        order_count: {$size: '$orders'}, //I get 'The argument to $size must be an array, but was of type: object' error
    }
},
])

the result I expected is:

{order_count:2, total_values:1000} //For example document
{order_count:3, total_values:1500} 
{order_count:5, total_values:2500}

1 Answer 1

1

I found a way to get the results that I wanted. Here is the code

db.users.aggregate([
    {
        $project: {
            _id: 1, orders: 1, order_count: { $size: '$orders' }
        }
    },
    { $unwind: '$orders' },
    {
        $project: {
            _id: '$_id', items: '$orders.items', order_count: '$order_count'
        }
    },
    { $unwind: '$items' },
    {
        $project: {
            _id: '$_id', sum: { $sum: '$items.value' }, order_count: '$order_count'
        }
    },
    {
        $group: {
            _id: { _id: '$_id', order_count: '$order_count' }, total_values: { $sum: '$sum' }
        }
    },
])

output:

{ _id: { _id: ObjectId("5dffc33002ef525620ef09f1"), order_count: 2 }, total_values: 1000 }
{ _id: { _id: ObjectId("5dffc33002ef525620ef09f2"), order_count: 3 }, total_values: 1500 }
Sign up to request clarification or add additional context in comments.

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.