Home > Mobile >  Sum all the fields in documents in MongoDB
Sum all the fields in documents in MongoDB

Time:12-05

I have documents with a number of tokens in text, one document for a text. I need to calculate a total token count across documents. I don't know the exact number and keys of these fields, so I cannot use $sum for each field individually.

For example, I have two documents:

{
    "count": {
        "a": 1,
        "b": 5,
        "c": 7
    }
}

{
    "count": {
        "a": 4,
        "c": 2,
        "d": 6
    }
}

I want to aggregate them and get

{
    "count": {
        "a": 5,
        "b": 5,
        "c": 9,
        "d": 6
    }
}

As I understand, it is not possible, but I just wanted to make sure

CodePudding user response:

Maybe something like this:

db.collection.aggregate([
{
 $set: {
  count: {
    "$objectToArray": "$count"
  }
}
},
{
  $unwind: "$count"
},
{
  $group: {
  _id: "$count.k",
  v: {
    $sum: "$count.v"
  }
 }
 },
{
$project: {
  v: 1,
  k: "$_id",
  _id: 0
 }
},
{
$group: {
  _id: "total",
  count: {
    $push: {
      k: "$k",
      v: "$v"
     }
    }
  }
},
{
  $project: {
  _id: 0,
  count: {
    "$arrayToObject": "$count"
   }
  }
}
])

Explained:

  1. Convert the objects to array(to be easy to manipulate unknown number of fields )

  2. Unwind the array

  3. group by the keys , sum the values.

  4. project the necessary key / values.

  5. group all in single array

  6. Project to convert the array to object as per the expectations

Playground

  • Related