具有多个字段的Spring数据mongoDB推送操作不起作用

时间:2019-03-18 14:19:49

标签: mongodb spring-boot aggregation

我在MongoDB as中有一组数据对象-

[
    { "status" : "passed", "version" : "124" , "value" : 6 },
    { "status" : "passed", "version" : "123" , "value" : 10 },
    { "status" : "failed", "version" : "123" , "value" : 16 }
]

我想以-

的格式获取它
[
    { 
    version: 124,
    "series" :[ 
        { 
            "name" : "passed", 
            "value" : 6 
        }
      ]
    },
    {
    version: 123,
    "series" : [
         { 
             "name" : "passed", 
             "value" : 10 
         },
         { 
             "name" : "failed", 
             "value" : 16 
         }
      ]
    }
]

我应该如何编写查询? 我写了

这样的查询

我写了一个查询,例如:

Aggregation.group("version").push(new BasicDBObject("name","$status").append("value", "$value")).as("series");

使用上面的汇总查询,我会得到:

[
    { 
    version: 124,
    "series" :[ 
        { 
          "name" : null, 
          "value" : 6 
        }
      ]
    },
    {
    version: 123,
    "series" : [
         { 
           "name" : null, 
           "value" : 10
         },
         { 
           "name" : null, 
           "value" : 16 
         }
      ]
    }
]

状态的值似乎未在对象中获取。我该如何解决?

2 个答案:

答案 0 :(得分:1)

我的查询就像:

db.results.aggregate([{
     {
       "$group": {
             "_id": {
                  "status": "$status",
                  "version": "$version",
              },
             "count": {
                  "$sum": 1
              }
            }
        }, {
            $group: {
                _id: "$_id.version",
                "series": {
                    $push: {
                        "status": "$_id.status",
                        "value": "$count"
                    }
                }
            }
        }
    ]);

所以我必须将聚合查询添加为:

Aggregation.group("version").push(new BasicDBObject("_id", "$_id.status").append("value", "$value")).as("series");

答案 1 :(得分:0)

我尝试了mongo聚合。尝试在外壳中。 我不熟悉春天。

db.getCollection('Test1').aggregate([
{
$group:{
    _id:"$version",
    version:{$first:"$version"},
    series:{
        $push:{
            name:"$status",
            value:"$value"
            }
        }
    }
},
{$project:{_id:0}}
])