0
votes

I have been looking around and searching the internet, but I couldn't find an answer. Maybe I am wrong with my aggregation, please correct me if I am wrong.

supposedly I have a data like this

mongos> db.data_analytics.find().sort({_id:-1}).limit(1).pretty()

{
    "title" : "data weather currency",
    "time" : "Sun Dec 08 2013 04:01:51 GMT+0900 (JST)",
    "_id" : ObjectId("52a3709f52d744c201000ba6"),
    "dataAnalytics" : [
        {
            "keyItem" : "currency-yen-php",
            "currency" : 0.427044,
            "from" : "JPY",
            "to" : "PHP",
            "time" : "Sun Dec 08 2013 04:01:49 GMT+0900 (JST)",
            "key" : "currency"
        },
        {
            "keyItem" : "weather-akiruno",
            "main-temp" : "5.78",
            "main-temp_min" : "2.78",
            "main-temp_max" : "7.78",
            "weather-main" : "Clouds",
            "weather-description" : "scattered clouds",
            "time" : "Sun Dec 08 2013 04:01:50 GMT+0900 (JST)",
            "key" : "weather"
        },
    ],
    "__v" : 0
}

I want to group and count by "$dataAnalytics.currency", but I get an error in a Sharded environment like this

mongos> db.data_analytics.aggregate([{$unwind: "$dataAnalytics"}, {$group:{_id:"$dataAnalytics.currency", c: {$sum:1}}}])
{
    "code" : 16390,
    "ok" : 0,
    "errmsg" : "exception: sharded pipeline failed on shard jeanepaul_set_pi_debian_01: { errmsg: \"exception: invalid operator \"$const\"\", code: 15999, ok: 0.0 }"
}

I have tried doing this in replica set successfully, but no luck in sharded environment. what could be the problem?

I appreciate any help, and thank you for any help in advance!

2

2 Answers

0
votes

You're currently grouping by the entire dataAnalytics element, you need to add .currency (or some other individual field) to your _id like this:

db.data_analytics.aggregate([
    {$unwind: "$dataAnalytics"}, 
    {$group:{_id:"$dataAnalytics.currency", c: {$sum:1}}}])
0
votes

Sir Ian, if you can see this, I have solved the problem. I added a $match to my aggregate. and here's my result


    mongos> db.data_analytics.aggregate([{$unwind:"$dataAnalytics"},{$match:{"dataAnalytics.key":"currency"}},{$group:{_id:"$dataAnalytics.currency", total: {$sum:1}}}, {$limit:100}])
    {
        "result" : [
            {
                "_id" : 0.428345,
                "total" : 3
            },
            {
                "_id" : 0.428517,
                "total" : 7
            },
            {
                "_id" : 0.428511,
                "total" : 63
            },
            {
                "_id" : 0.42802,
                "total" : 7
            }
        ],
        "ok" : 1
    }

the error seems to be gone. Thank you again for the suggestion!