mongodb中总和的最大值

时间:2017-04-11 10:36:07

标签: mongodb sum max

下面的查询给出了每年模型的总和。我需要找到最大模型的年份。 (数据是制造商中的另一个数组)

    var config = {headers : {
            "Content-Type": "application/json; charset = utf-8;"
        }
    }; 

1 个答案:

答案 0 :(得分:1)

  1. 按年度分组
  2. 计算当年制作的型号总数
  3. 根据型号总和进行排序
  4. 将查询限制为1
  5. 现在你将获得最大型号的年份。

    所以你的Query(Java实现)将如下所示:

         // Group by Year
         DBObject groupFields = new BasicDBObject( "_id", "$_id.year");
    
         //Count total no of models made in that year
         groupFields.put("sum", new BasicDBObject( "$sum", "$manufacturers.data.modelName"));
    
         //Group the fields
         DBObject group = new BasicDBObject("$group", groupFields);
    
         //Sort in descending order inorder to get maximum models 
         DBObject sortFields = new BasicDBObject("sum", -1);
         DBObject sort = new BasicDBObject("$sort", sortFields );
    
         //Limit to one since you need the year when maximum models were made
         DBObject limit = new BasicDBObject("$limit", 1 );
         AggregationOutput output = myColl.aggregate(group,sort,limit);
    

    希望这有帮助。

    编辑输入:

    db.structure.aggregate([
    {$unwind : "$manufacturers"},
        {$group: {
            _id: {
                day:"$_id.year"
            },
            count: { $sum: "$manufacturers.data.modelName" }
        }},
        {$sort: {count : -1}},
        //Limit by 1 to get year when maximum models where made
        {$limit : 1},
        {$out : "out"}
    ]);