1

I have an object looks like this

{
    "_id" : {
        "import_type" : "MANUAL_UPLOAD",
        "supplier" : "jabino.de",
        "unit_price" : "0"
    },
    "statuses" : [ 
        {
            "status" : "DUPLICATED",
            "count" : 14
        }, 
        {
            "status" : "BLACKLISTED",
            "count" : 2
        }, 
        {
            "status" : "USABLE",
            "count" : 2239
        }, 
        {
            "status" : "INVALID_EMAIL_ADDRESS",
            "count" : 1
        }, 
        {
            "status" : "DUPLICATED",
            "count" : 14
        }, 
        {
            "status" : "BLACKLISTED",
            "count" : 2
        }, 
        {
            "status" : "USABLE",
            "count" : 2239
        }, 
        {
            "status" : "INVALID_EMAIL_ADDRESS",
            "count" : 1
        }
    ]
}

How I can sum all the count in the statuses array which has the same status without losing keys-values in _id. E.g. in this case

  • Duplicated: 28
  • Blacklisted: 4
  • Usable: 4478
  • Invalid email address: 2

1 Answer 1

5

You can use below aggregation

db.collection.aggregate([
  { "$unwind": "$statuses" },
  { "$group": {
    "_id": {
      "_id": "$_id",
      "statuses": "$statuses.status"
    },
    "count": { "$sum": "$statuses.count" }
  }},
  { "$group": {
    "_id": "$_id._id",
    "statuses": {
      "$push": {
        "status": "$_id.statuses",
        "count": "$count"
      }
    }
  }}
])
Sign up to request clarification or add additional context in comments.

2 Comments

Works. Thanks a lot.
2 more mins mate

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.