Mongodb聚合

时间:2014-03-06 09:44:54

标签: mongodb aggregation-framework

假设我们有一个像这样的学校列表:

[
{
    "school_name” : "School #1",
    "city” : "Frankfurt",
    "country” : "Germany",
},
{
    "school_name” : "School #2",
    "city” : "Frankfurt",
    "country” : "Germany",
},
{
    "school_name” : "School #3",
    "city” : "Madrid",
    "country” : "Spain",
},
{
    "School_name” : "School #4",
    "city” : "Barcelona",
    "country” : "Spain",
}

聚合框架是否有可能按国家/地区获得一个独特的城市列表:

[
{
 "country" : "Germany" 
 "cities" : [Frankfurt,Berlin, ...]
},
{
 "country" : "Spain",
 "cities" : [Madrid,Barcelona, ...]
}

2 个答案:

答案 0 :(得分:0)

简单。

db.collection.aggregate([
    {"$group": { 
        "_id": "$country",
        "cities": {"$addToSet": "$city" },
    }},
    {"$project": { 
        "_id": 0,
        "country": 1,
        "cities": 1
    }}
])

阅读文档中的aggregation pipline运算符。

答案 1 :(得分:0)

如果你想要"独特"列表,您必须使用" $ addToSet"而不是" $ push"如Neil所述。

db.collection.aggregate([
    {"$group": { 
        "_id": "$country",
        "cities": {"$addToSet": "$city" },
    }},
    {"$project": { 
        "_id": 0,
        "country": 1,
        "cities": 1
    }}
])