SuFi
SuFi

Reputation: 385

How to merge two aggregation queries into one

How can I merge these 2 queries into one:

Query 1

db.Response.aggregate([ 
    {
        "$and": [
            { "job_details.owner_id" : 428 },
            { "job_details.owner_type" : 'searches' }
        ]
    },
    {
        "$group": {
            "_id": "$candidate_city_name_string",
            "count": { "$sum": 1 }
        }
    }
])

Query 2

db.Response.aggregate([ 
    {
        "$and": [
            { "job_details.owner_id" : 428 },
            { "job_details.owner_type" : 'searches' }
        ]
    },
    {
        "$group": {
            "_id": "$skill",
            "count": { "$sum": 1 }
        }
    }
])

The result of this query like this output 1:

{
    "result": [
        { _id: 'Bangalore', count: 8 },
        { _id: 'cochi', count: 9 }
    ]
    "ok":1
}

output 2:

{
    "result": [
        { _id: 'java', count: 7 },
        { _id: 'python', count: 10 }
    ],
    "ok":1
}

How can I get these 2 results in one query?

I need an output like this:

Expected output:

 {
     "result": [
         "candidate_city_name_string": [
             { _id: 'Bangalore', count: 8 },
             { _id: 'cochi', count: 9 }
         ],
         "skill": [
             { _id: 'java', count: 7 },
             { _id: 'python', count: 10 }
         ]  
     ],
     "ok":1
 }

Is it possible? Somewhere I saw something about $facet but I didn't understand that.

Upvotes: 1

Views: 256

Answers (1)

SuFi
SuFi

Reputation: 385

db.Response.aggregate([
{"$match":{"$and":[{"job_details.owner_id" : 482},{"job_details.owner_type" : 'searches'}]}}, 
{$facet: {
    "candidate_sublocation_name_string": [ 
                        {"$group": {"_id":"$candidate_sublocation_name_string","count": {"$sum": 1 }}}
                      ],
    "skill": [ 
                        {"$group": {"_id":"$skill","count": {"$sum": 1 }}}
                      ]
        }}])

Upvotes: 1

Related Questions