0

I have a database structure which includes the following object:

"reactions": {
    "👊": [
        "5f3c569e70441a0017511fe2",
        "5f88d49dbf1b850017e28f4e",
        "5f488189b0c5970017aa8c7a"
    ],
    "😋": [
        "5f539086cfb52a00176089ed"
    ]
}

I want to be able to count the "number of reactions" (a total of all the nested elements) - so in this case, the expected result would be 4.

I tried the following, and this successfully counts the number of keys - the result is 2, but not the total number of values - which should be 4.

db.collection("posts").aggregate([{
    {
        $addFields: {
            reactionsArray: {
                $objectToArray: "$reactions"
            }
        }
    },
    {
        $addFields: {
            numberOfReactions: {
                $sum: {
                    $size: "$reactionsArray.v"
                }
            }
        }
    }
])

2 Answers 2

2

Use $reduce to sum size of each element of your array.

db.collection.aggregate([
  {
    $addFields: {
      reactionsArray: {
        $objectToArray: "$reactions"
      }
    }
  },
  {
    "$project": {
      reactionsSize: {
        $reduce: {
          input: "$reactionsArray",
          initialValue: 0,
          in: {
            "$add": [
              "$$value",
              {
                $size: "$$this.v"
              }
            ]
          }
        }
      },
      
    },
    
  }
])

MongoDB Playground

Sign up to request clarification or add additional context in comments.

Comments

1

You have to $unwind reactionsArray and then use $group to get total count

db.collection.aggregate([
  {
    $addFields: {
      reactionsArray: {
        $objectToArray: "$reactions"
      }
    }
  },
  {
    $unwind: "$reactionsArray"
  },
  {
    $group: {
      _id:"$_id",
      numberOfReactions: {
        $sum: {
          $size: "$reactionsArray.v"
        }
      }
    }
  }
])

MongoDB Playground

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.