MongoDB-复合群

MongoDB-复合群,mongodb,pymongo,Mongodb,Pymongo,我收集了文件,其中我的文件如下: { "_id" : ObjectId("52fe1d364b5ab856eea75ebc"), "elevation" : 1855, "name" : "Kud", "country" : "India", "lon" : 75.28, "lat" : 33.08, "isPartOf" : [ "Jammu and Kashmir", "Udhampur district

我收集了文件,其中我的文件如下:

{
    "_id" : ObjectId("52fe1d364b5ab856eea75ebc"),
    "elevation" : 1855,
    "name" : "Kud",
    "country" : "India",
    "lon" : 75.28,
    "lat" : 33.08,
    "isPartOf" : [
        "Jammu and Kashmir",
        "Udhampur district"
    ],
    "timeZone" : [
        "Indian Standard Time"
    ],
    "population" : 1140
}
pipeline = [
            {"$match": {"isPartOf":{"$exists":1}, "country":{"$exists":1}}},
            {"$unwind": "$isPartOf"},
            {"$group":{"_id": {"isPartOf": "$isPartOf", "country": "$country"}, "avgRegionalPopulation": {"$avg":"$population"}}},
            {"$sort": {"avgRegionalPopulation":-1}}
            ]
我有兴趣找到“城市集合中所有国家的平均区域城市人口”。我的聚合管道命令如下所示:

{
    "_id" : ObjectId("52fe1d364b5ab856eea75ebc"),
    "elevation" : 1855,
    "name" : "Kud",
    "country" : "India",
    "lon" : 75.28,
    "lat" : 33.08,
    "isPartOf" : [
        "Jammu and Kashmir",
        "Udhampur district"
    ],
    "timeZone" : [
        "Indian Standard Time"
    ],
    "population" : 1140
}
pipeline = [
            {"$match": {"isPartOf":{"$exists":1}, "country":{"$exists":1}}},
            {"$unwind": "$isPartOf"},
            {"$group":{"_id": {"isPartOf": "$isPartOf", "country": "$country"}, "avgRegionalPopulation": {"$avg":"$population"}}},
            {"$sort": {"avgRegionalPopulation":-1}}
            ]

但我似乎错过了什么。由于“立陶宛”的“平均人口”应为14750.784447977203。我在管道命令中遗漏了什么?

您遗漏了每个国家步骤的平均人口。这是一个正确的聚合管道命令:

pipeline = [
            {"$match": {"isPartOf":{"$exists":1}, "country":{"$exists":1}}},
            {"$unwind": "$isPartOf"},
            {"$group" : {"_id": {"isPartOf": "$isPartOf", "country": "$country"}, "avgregion":{"$avg":"$population"}}},
            {"$group": {"_id": "$_id.country", "avgRegionalPopulation": {"$avg":"$avgregion"}}},
            {"$sort": {"country":-1}}
            ]