Home > Blockchain >  MongoDB: How to find objects and return a sum of values
MongoDB: How to find objects and return a sum of values

Time:03-15

I saw similar questions here, but can't really figure this problem out. I've got the following orders collection:

{
  orders: [
    {
      userId: "abc",
      orderId: "123",
      balance: 2,
    },
    {
      userId: "abc",
      orderId: "123",
      balance: 5,
    },
    {
      userId: "def",
      orderId: "456",
      balance: 1,
    },
    {
      userId: "abc",
      orderId: "456",
      balance: 3,
    },
  ];
}

I need an aggregation query that would return the sum of balances for the given userId AND orderId. For this following example, given userId = "abc" and orderId = "123", the result of that query would be 7. So far, I have tried $map and $sum, but can't really put together the structure of the query.

How can I get the sum of the balances given the userId AND orderId ?

CodePudding user response:

I managed to work it out with this:

db.collection.aggregate([
  {
    $match: {
      "userId": "abc",
      "orderId": "123"
    }
  },
  {
    $group: {
      _id: "$userId",
      total: {
        $sum: "$amount"
      }
    }
  },
  {
    $sort: {
      total: -1
    }
  }
])

CodePudding user response:

orders.aggregate([
    {
    "$group": {
      "_id": {
        "user": "$userId",
        "order": "$orderId"
      },
      "amount": {
        "$sum": "$balance"
      }
    }
  }
])
  • Related