2

I have a set of data objects in MongoDB as-

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

and i want to get it in a format like -

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

how should i write the query? I wrote query like

I have written a query like:

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

using the aggregate query above, I'm getting like:

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

It seems that the value of the status is not taken in the object. How can I resolve this?

1
  • I am doing the same and it worked well for me. What is the version of Spring-data-mongodb used by you? Commented Mar 18, 2019 at 15:26

2 Answers 2

1

My Query is like:

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

So I have to add the aggregation query as:

Aggregation.group("version").push(new BasicDBObject("_id", "$_id.status").append("value", "$value")).as("series");
Sign up to request clarification or add additional context in comments.

Comments

0

I tried with mongo aggregation. Try in the shell. I am not familiarised with spring.

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

1 Comment

Thanks for your reponse, but I need spring boot mongoDB query.

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.