如何在搜索中对整个文档中的字段求和?

时间:2019-11-10 14:48:03

标签: mongodb

我想总结一个元素的总数,可以将其值压入数组。 基本上,我有另一种类型的文档,我想将其数据与求和值一起推入数组。

我有一些示例文档:-

  { 
      school:"mnps",
      name: 'sweta',
      totalimages: 100,
      state: 'downloaded',
  },
  {  
      school:"mnps",
      name: 'sweta',
      totalimages: 400,
      state: 'allocated',
  },

  {  
      school:"mnps",
      name: 'sweta',
      totalimages: 200,
      state: 'allocated'
  },
  { 
      school:"mnps",
      name: 'sweta',
      totalimages: 600,
      state: 'allocated',
  },
  { 
      school:"mnps",
      name: 'peter',
      totalimages: 1000,
      state: 'allocated',
  }   

Something that I have tried:-

 return db.aggregate([
      {
           $match:{school:"mnps"}
       },
       {
           $group:
             {
                 "_id":{"name":"$name","state":"$state"},
                 "totalcount":{$sum:"$totalimages"}      
              }
        },
        {
           "$group":
              {
                 "_id":"$_id.name",
                 "states":{
                    "$push":{
                        "k":"$_id.state","v":"$totalcount"
                     }
                   }
              }
         },
        {"$addFields":{
            "states":{
                "$arrayToObject":"$states"
             }
         }
    ])

Current Result :
    [ 
        { _id: 'sweta', states: { allocated: 400, downloaded: 100 } },
        { _id: 'peter', states: { allocated: 1000 } },
    ]

 Expected result : 

    [ 
         { _id: 'sweta', states: { allocated: 1200, downloaded: 100 } },
         { _id: 'peter', states: { allocated: 1000 } },
    ]

仅获取组合的第一个文档。如果只有一个文档用于合并,则计数正确,但是对于多个文档,计数不正确。 例如:-

1.  peter only 1 state is there i.e allocated so the count is correct.
2.  sweta 2 states are there allocated and downloaded. For downloaded the count is correct but for allocated the count is not correct because for allocated there is more than 1 document.

0 个答案:

没有答案