pbjork
pbjork

Reputation: 616

Group and aggregate on sub document in mongodb

OBS! Noob question probably :)

Given the following data, how can I query and return a summary for each index?

[
{
    "title": "test",
    "indexes":[
        { "id":1, "value": 0.5764860139860139860139860140 },
        { "id":2, "value": 0.3083479020979020979020979020 },
        { "id":3, "value": 0.1151660839160839160839160838 }
    ]
},
{
    "title": "test",
    "indexes":[
        { "id":1, "value": 0.5764860139860139860139860140 },
        { "id":2, "value": 0.3083479020979020979020979020 },
        { "id":3, "value": 0.1151660839160839160839160838 }
    ]
},
{
    "title": "test",
    "indexes":[
        { "id":1, "value": 0.5764860139860139860139860140 },
        { "id":2, "value": 0.3083479020979020979020979020 },
        { "id":3, "value": 0.1151660839160839160839160838 }
    ]
},
{
    "title": "test",
    "indexes":[
        { "id":1, "value": 0.5764860139860139860139860140 },
        { "id":2, "value": 0.3083479020979020979020979020 },
        { "id":3, "value": 0.1151660839160839160839160838 }
    ]
}

]

I.e. I want to produce something like this:

index.id:1, total: 2.305...
index.id:2, total: 1.233...
etc

Upvotes: 0

Views: 26

Answers (2)

vicky
vicky

Reputation: 415

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

try this query

you will get like this

[
  {
    "_id": 2,
    "total": 1.2333916083916083
  },
  {
    "_id": 1,
    "total": 2.305944055944056
  },
  {
    "_id": 3,
    "total": 0.4606643356643357
  }
]

Upvotes: 1

varman
varman

Reputation: 8894

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

Working Mongo playground

Upvotes: 1

Related Questions