skip to Main Content

i have a mongodb recor which looks like this .

[
  {
    "_id": {
      "$oid": "64a5a396ec152ab4f5e1c60c"
    },
    "firstName": "Ram",
    "lastName": "Shayam",
    "email": "[email protected]",
    "transactions": [
      {
        "amount": 22,
        "date": "21/7"
      },
      {
        "amount": 12,
        "date": "21/7"
      },
      {
        "amount": 50,
        "date": "19/7"
      },
      {
        "amount": 100,
        "date": "19/7"
      }
    ]
  }
]

now i gave to filter transactions on the basis of date by doing these operations:

db.collection.aggregate([
  {
    $match: {
      firstName: "Ram"
    }
  },
  {
    $unwind: "$transactions"
  },
  {
    $match: {
      "transactions.date": {
        $eq: "21/7"
      }
    }
  },
  {
    $group: {
      _id: "$_id",
      list: {
        $push: "$transactions"
      }
    }
  }
])

and getting shorted array with transactions of only given dates like this…

[
  {
    "_id": ObjectId("64a5a396ec152ab4f5e1c60c"),
    "list": [
      {
        "amount": 22,
        "date": "21/7"
      },
      {
        "amount": 12,
        "date": "21/7"
      }
    ]
  }
]

**now how to get the total amount spend on that day using some other operations.
like i want to get 34 as output by doing operations.

here is the playground link for more details.**

how to get the total amount spend on that day using some operations from a array of objects with amount and date of amount.

2

Answers


  1. Use $sum(aggregation)

    db.collection.aggregate([
      {
        $match: {
          firstName: "Ram"
        }
      },
      {
        $unwind: "$transactions"
      },
      {
        $match: {
          "transactions.date": {
            $eq: "21/7"
          }
        }
      },
      {
        $group: {
          _id: "$_id",
          list: {
            $push: "$transactions"
          },
          total: {
            $sum: "$transactions.amount"
          }
        }
      }
    ])
    

    mongoplayground

    Login or Signup to reply.
  2. added $sum to count

    db.collection.aggregate([
      {
        $match: {
          firstName: "Ram"
        }
      },
      {
        $unwind: "$transactions"
      },
      {
        $match: {
          "transactions.date": {
            $eq: "21/7"
          }
        }
      },
      {
        $group: {
          _id: "$_id",
          list: {
            $push: "$transactions"
          },
          count: {
            $sum: "$transactions.amount"
          }
        }
      }
    ])
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search