Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Complex aggregate command MongoDB

I have tons of documents in a Mongo database with the following structure:

{
    "_id" : {
        "birthDate" : "1978-08-09",
        "name" : "Peter"
},
    "value" : {
        "types" : {
            "euro" : 90,
            "unknown" : 2,
            "dollar" : 3
        }
    }
}

Not all documents contain all types (i.e.: some of them only have euro or don't have the unknown field).

I want to count the number of occurrences of each type for a specific name with the aggregate framework.

I have this:

db.collection.aggregate({$match: {_id : {name:"John"}}}, {$group: {_id: '', euro: {$sum: '$value.types.euro'}, dollar: {$sum: '$value.types.dollar'}, unknown: {$sum: '$value.types.unknown'}}})

But it is returning:

{ "result" : [ ], "ok" : 1 }

My question is: How can I count the type of each coin for a specific name with the Mongo's aggregate framework? Would it be also possible to get a list for every name in the form:

"result" : [
    {
        "name" : "Peter",
        "dollar" : 1,
        "euro" : 12,
        "unknown" : 4

    }
]

"result" : [
    {
        "name" : "John",
        "dollar" : 4,
        "euro" : 10,
        "unknown" : 3

    }
]

I am using MongoDB with the Java driver, so if the answer is in Java code it would be perfect.

like image 310
user3083022 Avatar asked Mar 03 '26 09:03

user3083022


1 Answers

You can use the following query to group by name & count coins :

db.collection.aggregate(
  {$group : {_id : "$_id.name", 
             dollar : {$sum : "$value.types.dollar"}, 
             euro : {$sum : "$value.types.euro"}, 
             unknown : {$sum : "$value.types.unknown"}}}
)

Also if you want to find the number of coins for specific person you can use following query :

db.collection.aggregate(
  {$match : {"_id.name" : "John"}},
  {$group : {_id : "$_id.name", 
             dollar : {$sum : "$value.types.dollar"}, 
             euro : {$sum : "$value.types.euro"}, 
             unknown : {$sum : "$value.types.unknown"}}}
)
like image 71
Parvin Gasimzade Avatar answered Mar 06 '26 02:03

Parvin Gasimzade