如何使用mongodb查询获取集合中的列的单独计数?

时间:2016-08-09 14:20:19

标签: node.js mongodb mongoose aggregation-framework mongodb-aggregation

我是MongoDB的初学者。我需要从一个MongoDB查询中获取单个列数。

例如,我有一个包含字段hotelCollection的集合cityid , starRating, area, locality。现在我将参数cityid作为123传递给查询,我需要将结果提取为:

result: {
    starCount: {
        1star: 5,
        2star: 6,
        3star: 5
    },
    areaCount: {
        area1: 4,
        area2: 12
    },
    localityCount: {
        locality1: 10,
        locality2: 6
    }
}

我尝试使用aggregate查询,但最后我只获得了一个列数。所以我最终写了4个aggregate查询。现在我面临着性能问题。我做了很多谷歌搜索,但无法找到任何解决方案。请帮我解决这个问题。

1 个答案:

答案 0 :(得分:0)

您需要在 $sum 运算符中使用条件表达式来检查cityid , starRating, area, locality键'使用比较运算符 $eq

的值

您可以通过添加以下表达式来重构您的管道:

db.hotelCollection.aggregate([
    { "$match": { "cityid": 123 } },
    {
        "$group" : {
            "_id": null, 
            "1star": {
                "$sum": {
                    "$cond": [
                        { "$eq": ["$starRating", 1]  },
                        1, 0
                    ]
                }
            },
            "2star": {
                "$sum": {
                    "$cond": [
                        { "$eq": ["$starRating", 2]  },
                        1, 0
                    ]
                }
            },
            "3star": {
                "$sum": {
                    "$cond": [
                        { "$eq": ["$starRating", 3]  },
                        1, 0
                    ]
                }
            },
            "area1": {
                "$sum": {
                    "$cond": [
                        { "$eq": ["$area", 1]  },
                        1, 0
                    ]
                }
            },
            "area2": {
                "$sum": {
                    "$cond": [
                        { "$eq": ["$area", 2]  },
                        1, 0
                    ]
                }
            },
            "locality1": {
                "$sum": {
                    "$cond": [
                        { "$eq": ["$locality", 1]  },
                        1, 0
                    ]
                }
            },
            "locality2": {
                "$sum": {
                    "$cond": [
                        { "$eq": ["$locality", 2]  },
                        1, 0
                    ]
                }
            }
        }
    },
    { 
        "$project" : { 
            "_id": 0,
            "starCount": {
                "1Star": "$1star",
                "2Star": "$2star",
                "3Star": "$3star"
            },
            "areaCount": {
                "area1": "$area1",
                "area2": "$area2"
            },
            "localityCount": {
                "locality1": "$locality1",
                "locality2": "$locality2"
            }               
        } 
    }
])