0

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

2
  • Are you looking for highest first and second and third OR the highest sum of first, second, and third? E.g. a doc with {first: 10, second: 10, third: 10} might have all the individual highest, but {first: 200, second: 0, third: 0} has a higher sum across the fields. Commented Nov 25, 2017 at 19:36
  • @BuzzMoschetti Highest sum of first, second and third is what i am looking for Commented Nov 25, 2017 at 19:58

2 Answers 2

1

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"}
        }
    }
}
])
Sign up to request clarification or add additional context in comments.

Comments

0

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

1 Comment

Ah, yes! Thank you so much.. :)

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.