0

我正在使用 golang 和 mongodb。下面是我的 go 代码

matchStage := bson.M{"$match": bson.M{'country':'India'}}
groupByStage := bson.M{"$group": bson.M{
        "_id":             "$state",
        "city_count": bson.M{"$sum": 1},
    }}
pipeline := getCollection.Pipe([]bson.M{
        matchStage,
        groupByStage,
    })

 document := []bson.M{}
 err = pipeline.All(&document)

我得到每个州的城市计数,但我想获得分组状态的总数。这只是一个例子,但我想获得类似的数据。所以在循环旁边有任何解决方案来获取分组数据的总数而不是每个分组数据计数?

我的输出就像 {'state1':3,'state2':4,'state3':1}但我只想要'3' as count

4

1 回答 1

0

首先,您似乎正在使用 mgo 或其他版本。我强烈建议您使用mongodb 的官方 go 驱动程序

有两种方法可以回答您的问题:

如果您只想要计数不是您基本上需要的:

states := []string{}
err := getCollection.Find(bson.M{'country': 'India'}).Distinct("state", &states)
fmt.Printf("%d\n", len(states))

如果您想要每个州的州数以及计数 - 可以添加第二组。

matchStage := bson.M{"$match": bson.M{'country':'India'}}
groupByStage := bson.M{"$group": bson.M{
        "_id": bson.M{
                 "country": "$country",
                 "state": "$state",
        },
        "city_count": bson.M{"$sum": 1},
    }}
groupByStage2 := bson.M{"$group": bson.M{
        "_id": "$_id.country",
        "city_counts": bson.M{
            "$push": bson.M{
                 "state": "$_id.state",
                 "city_count": "$city_count",
             },
        },
        "state_count": bson.M{"$sum": 1},
    }}
pipeline := getCollection.Pipe([]bson.M{
        matchStage,
        groupByStage,
        groupByStage2,
    })

 document := []bson.M{}
 err = pipeline.All(&document)

你应该得到这样的东西

[{
    "_id": "India",
    "city_counts": [{'state1':3,'state2':4,'state3':1}],
    "state_count": 3
}]
于 2020-08-26T07:47:53.953 回答