1

A user can add multiple products and multiple users can request that product. For each product I have an array of objects which holds the user ID's of the users who requested that product. I am trying to get a sum of all requests eg: (made up object id's for simplicity, I know they aren't realistic)

Below I have 2 products, one with a single request, and the second product with 2 requests, therefore this user has 2 products and 3 requests. I am trying to get the value of 3.

_id: ObjectId("12323443463")
userId: ObjectId("88888888")
title: "Product 1"
requests: Array
0: Object
_id: ObjectId("89766876")
userId: ObjectId("09795675")


_id: ObjectId("9878754")
userId: ObjectId("88888888")
title: "Product 2"
requests: Array
0: Object
_id: ObjectId("89766876")
userId: ObjectId("09795675")

1: Object
_id: ObjectId("66445547676")
userId: ObjectId("7765543434")

I tried this:

  Product.aggregate([
    { $match: { userId: req.user._id }},
    { $group: { _id: "$requests.userId", totals: { $sum: 1 } } }
  ])

If I console.log it I get:

[ { _id: [ 5c375260a6f58308e510711a, 5c25cddc73d10c02a75b3d55 ],
    totals: 1 },
  { _id: [ 5c375260a6f58308e510711a ], totals: 1 } ]

It is correct in that it gives me the 3 id's of the users that requested the product. However, I really just want the value of 3 as a result of the query.

1 Answer 1

1

You can use below aggregation

Product.aggregate([
  { "$match": { "userId": req.user._id }},
  { "$group": { "_id": null, "totals": { "$sum": { "$size": "$requests" } } } }
])

Basically you need to $sum the $size of the requests array

4
  • 1
    thank you. console.log() is giving me a value of 3. Why would someone downvote you for this answer?? Jan 16, 2019 at 19:12
  • 1
    just one thing though. This is giving me back an array. Since I only need the sum, is there a way to get it back so it isn't an array? I know I can access it like console.log(product[0].totals); but was just wondering. Jan 16, 2019 at 19:15
  • 1
    No aggregation only returns as array. You have to go with the 0th index
    – Ashh
    Jan 16, 2019 at 19:17
  • 1
    Aha, I see. Thanks for the answer, it has helped me immensely. Jan 16, 2019 at 19:17

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.