Sad Mad
Sad Mad

Reputation: 77

MongoDB Aggregation Query - Group aggregate field error

I have a MongoDB collection, with one document such as -

{
    "_id" : ObjectId("5a187babdbf0a03cdca0d0bc"),
    "aggregationDate" : "2017-10-31",
    "ipaddress" : "10.65.66.184",
    "first" : {
        "count" : 3
    },
    "second" : {
        "count" : 2
    },
    "third" : {
        "count" : 3
    },
}

There are around 30000 such documents, with around 1000 new ones generated every day. I want to display the "ipaddress" having highest activity, which is defined as highest count of "first", "second" and "third".

I looked up aggregation queries and wrote the following one -

db.collection.aggregate({ $group : { ipaddress: "$ipaddress", 
                          max: { $max : [ "$first.count", "$second.count", "$third.count" }}});

I unfortunately get an error -

"errmsg" : "exception: the group aggregate field 'ipaddress' must be defined as an expression inside an object",

Can someone please help me with this error and also with writing an aggregation query for my requirement? Thanks

Upvotes: 0

Views: 2286

Answers (2)

Buzz Moschetti
Buzz Moschetti

Reputation: 7578

This should do the trick. You need the $add function in there too.

db.foo.aggregate([
  {$group: {_id: "$ipaddress",
            max: { $max: {$add: [ "$first.count", "$second.count", "$third.count"] } }
           }
  }
]);

Upvotes: 0

Alex P.
Alex P.

Reputation: 3171

Yeah that's because in the $group pipeline you can't have things like that

ipaddress: "$ipaddress"

The field ipaddress has to be accompanied by an accumulator operator. The documentation here is excellent have a look here

If you mean to group by ipaddress then you have to write it like that:

_id: "$ipaddress"

Your $max operator wont work this way either. This is the way you use it in the $project pipeline not in the $group. Please take a look here

So your aggregation would have to look like this:

db.collection.aggregate([
{
    $group: 
    {
        _id: "$ipaddress",
        max: {
            $max: {first: "$first.count", second: "$second.count", third: "$third.count"}
        }
    }
}
])

Upvotes: 1

Related Questions