1

I have a mongo query that looks like this:

db.myCollection.aggregate([ { 
    $group: { 
        _id: null,
        price: {
            $sum: "$price"
        },
        inventory: {
            $sum: "$inventory"
        }
    }
}])

Which returns

{
    "_id" : null,
    "price" : 26,
    "inventory" : 5,
}

I would like a query which would rather return something like this:

[
    {
        name: "price",
        amount: 26
    },
    {
        name: "inventory",
        amount: 5
    }
]

EDIT: How would I write this in Java with Spring Data? I can group and sum but don't know how to project it?

Aggregation aggregation = newAggregation(
                group("$id")
                        .sum("price").as("price")
                        .sum("inventory").as("inventory")
);

2 Answers 2

1

You'll need to use $project. It allows us to define which fields will be returned, as well as their format.

db.myCollection.aggregate([{ 
    $group: { 
        _id: null,
        price: {
            $sum: "$price"
        },
        inventory: {
            $sum: "$inventory"
        }
    }
},
{
    $project: {
        _id: 0 //removes _id from result
        something: [
            {name: "price", amount: "$price"},
            {name: "inventory", amount: "$inventory"}
        ]    
    }
}])

That will give you:

{
    "something" : [ 
        {
            "name" : "price",
            "amount" : 26
        }, 
        {
            "name" : "inventory",
            "amount" : 5
        }
    ]
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks! Any idea how to convert this to a Spring query? Updated my post
Sorry, man. Unfortunately, I don't have any experience on Spring.
0

You can use below aggregation

db.collection.aggregate([
  { "$project": {
    "data": {
      "$map": {
        "input": { "$objectToArray": "$$ROOT" },
        "in": { "name": "$$this.k", "amount": "$$this.v" }
      }
    }
  }},
  { "$unwind": "$data" },
  { "$replaceRoot": { "newRoot": "$data" }},
  { "$match": { "amount": { "$ne": null }}
  }
])

Comments

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.