如何将两个聚合查询合并为一个

时间:2016-11-10 07:51:30

标签: python mongodb mongodb-query pymongo aggregation-framework

如何将这两个查询合并为一个:

查询1

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

查询2

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

此查询的结果如下 输出1:

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

输出2:

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

如何在一个查询中获得这两个结果?

我需要这样的输出:

预期输出:

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

有可能吗?在某处,我看到了$facet的一些内容,但我对此并不了解。

1 个答案:

答案 0 :(得分:1)

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