user1673091
user1673091

Reputation: 31

Mongodb Groupby Aggregate and addition query together

i am taking forward my earlier question MongoDB GroupBy

After using the aggregate function i get what i want ,now i want to add some query parameters to that aggregate function and the query should be applied to result of aggregate i.e for example for entity_id "123" , there are 4 years val

"2010","2011","2012","2013"

after applying the aggregate function as per last question get "2013" with entity id "123" ,which is absolutely correct.

Now i want to add extra query ,which should be like - "entity_id "123" AND year "2013" AND "extra_query".

I tried using $match but it was taking as "entity_id" 123 AND Extra query.

i have 2 collections in my db

collection 1.

{
"entity_id":123,
"added_by":"a",
},
{
"entity_id":321,
"added_by":"b",
},

and collection 2

{
"entity_id":123,
"year":"2014",
"profit_val":2000,
},
{
"entity_id":123,
"year":"2013",
"profit_val":1000,
},
{
"entity_id":123,
"year":"2012",
"profit_val":500,
},
{
"entity_id":123,
"year":"2011",
"profit_val":100000,
},

so when i search "profit_val" > 10000 , i get result as "entity_id" = 123 , BUT this result is wrong as i want to look this condition only with max year of the entity. inshort i want to group by max year , which i already did ,answer given here now i want to add query to this "grouped" result only.

I hope this will make you understand what i am looking for.

Upvotes: 0

Views: 79

Answers (1)

Indrajeet
Indrajeet

Reputation: 647

What I understood from the question is you want something like this.

> db.collection2.aggregate([
    {
        $sort: {
            "year": 1
        }
    },
    {
        $group: {
            _id: "$entity_id",
            year: {
                $max: "$year"
            },
            profit_val: {
                $last: "$profit_val"
            }
        }
    },
    {
        $match: {
            "profit_val": {
                "$gt": 10000
            }
        }
    }
])

Upvotes: 1

Related Questions