user3083022
user3083022

Reputation: 569

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.

Upvotes: 3

Views: 1727

Answers (2)

Anthonny
Anthonny

Reputation: 1591

To count the type of each coin for a specific name, you can do that :

db.collection.aggregate([
{
    $match: {'_id.name' : "John"}
}, 
{
    $project: {
        _id: 1,
        euro: {$cond: [ { $eq: [ '$value.types.euro', undefined ]} , 0, 1 ]},
        dollar: {$cond: [  { $eq: [ '$value.types.dollar', undefined ]} , 0, 1 ]},
        unknown: {$cond: [ { $eq: [ '$value.types.unknown', undefined ]}, 0, 1 ]}
    }  
},
{
    $group: {_id: "$_id.name", euro: {$sum: '$euro'}, dollar: {$sum: '$dollar'}, unknown: {$sum: '$unknown'}}
}
])

Upvotes: 1

Parvin Gasimzade
Parvin Gasimzade

Reputation: 26012

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"}}}
)

Upvotes: 3

Related Questions