Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB: Sum of all items in referenced collection

Tags:

mongodb

I've got some issues getting the balance of all my accounts. All accounts have references to different deposit items in deposits collection.

Accounts collection:

[{
    "_id": "56b1ce63315748b44f1174e1",
    "name": "Foo bar",
    "deposits": [
        {
            "$oid": "56b1ce78315748b44f1174e2"
        }
    ]
}]

Deposits collection:

{
    "_id": {
        "$oid": "56b1deb84f40bfa435e22f3f"
    },
    "account": {
            "$oid": "56b1dea34f40bfa435e22f3e"
    },
    "amount": 300,
    "date": {
        "$date": "2016-02-01T00:00:00.000Z"
    }
}

I've tried to aggregate the query but it always returns balance: 0. I guess I need to populate the item before the use of aggregate. But how do I do that?

Accounts.aggregate([
    { $unwind: "$deposits" },
    {
        $group: {
            _id: "$_id",
            name: { "$first": "$name" },
            balance: { $sum: "$deposits.amount" }
        }
    }])

Solution:

{
    $lookup:
    {
        from: 'deposits',
        localField: 'amount',
        foreignField: 'deposits',
        as: 'deposits'
    },
},
{ $unwind: "$deposits" },
{
    $group: {
        id: "$_id",
        name: { "$first": "$name" },
        balance: { $sum: "$deposits.amount" }
    }
}
like image 630
bjorkblom Avatar asked Feb 01 '26 09:02

bjorkblom


1 Answers

You need to use the $lookup operator in order to join the two collections, your current approach doesn't work. The $lookup operator is only available in Mongo 3.2 and higher.

{
   $lookup:
     {
       from: <collection to join>,
       localField: <field from the input documents>,
       foreignField: <field from the documents of the "from" collection>,
       as: <output array field>
     }
}
like image 89
Alex Avatar answered Feb 04 '26 01:02

Alex



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!