0

I am trying to sum values from different objects. Each object has its ID, but the IDs can repeat in some objects. What I need to do now is sum the values from the objects that have the same ID.

Does someone have an idea for me? I tried to use mongoose aggregate, but with no success.

Let's suppose I have the objects below.

const array = [
  { _id: "123456", value: 30 },
  { _id: "123456789123456789", value: 12 },
  { _id: "123456", value: 25 },
];

I would need something that brings up the following result:

==>  id: 123456
     value: 55

==>  id: 123456789123456789
     value: 12
4
  • are the objects grouped inside an array? Commented Mar 5, 2023 at 4:16
  • Hello, yeah. Objects are grouped inside an array Commented Mar 5, 2023 at 4:18
  • stackoverflow.com/questions/51971373/… Commented Mar 5, 2023 at 4:24
  • Do you want to do this in javascript or with an aggregation pipeline and have the MongoDB server do it? If you want to use a pipeline, would you show a few example documents from your collection? Commented Mar 5, 2023 at 13:35

3 Answers 3

1

Reduce the array into a map. Conveniently, map.set returns the map, so it's just a one-liner.

const array = [{ _id: "123456", value: 30 }, { _id: "123456789123456789", value: 12 }, { _id: "123456", value: 25 }];

const sums = array.reduce((map, object) => map.set(object._id, map.get(object._id) ?? object.value), new Map());

console.log(sums.get("123456"));
console.log(sums.get("123456789123456789"));

// convert to normal object

const sumsAsNormalObject = Object.fromEntries([...sums.entries()]);

console.log(sumsAsNormalObject);

Confused about syntax? See nullish coalescing and spread syntax. You can also convert the map into a plain object if you wanted to.

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

Comments

0

its impossible to have duplicate _id in mongodb, but you can change that to something like dataId, id or else

example:

[
  {
    _id: 1,
    id: 123456,
    value: 30
  },
  {
    _id: 2,
    id: 123456789123456789,
    value: 12
  },
  {
    _id: 3,
    id: 123456,
    value: 25
  }
]

then with wongo would be like:

db.collection.aggregate([
  {
    "$group": {
      "_id": "$id",
      "value": {
        "$sum": "$value"
      }
    }
  }
])

MONGO-PLAYGROUND

Note: if some data can be handle by resources/database, use it instead. otherwise, create a function to handle it.

Comments

0

For each object, it checks whether the "result" object already has a property with the same _id as the current object being looped over.

    const array = [
      { _id: "123456", value: 30 },
      { _id: "123456789123456789", value: 12 },
      { _id: "123456", value: 25 },
    ];
    
    const result = {};
    
    array.forEach(item => {
      if(result[item._id]) {
        result[item._id] += item.value;
      } else {
        result[item._id] = item.value;
      }
    });
    
    console.log(result);

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.