gpt4 book ai didi

python - MongoDB 分组

转载 作者:行者123 更新时间:2023-12-03 15:59:27 25 4
gpt4 key购买 nike

我正在尝试计算按性别分组的平均年龄。预期输出应该是

{'_id': {'gender': 'M'},{'avg': '27.1}}
{'_id': {'gender': 'F'}},{'avg': '29.0}}

这是我的代码

pipeline = [
{
"$project" : {
"_id" : {'gender':"$gender"},
"avg": {"$avg":"$age"},
}
},
{"$group" : {"_id":"$_id"}},

]

for doc in db.user.aggregate(pipeline):
print(doc)

现在的输出是:

{'_id': {'gender': 'M'}}
{'_id': {'gender': 'F'}}

如有任何帮助,我们将不胜感激!我知道这可能很容易......

最佳答案

以下管道将为您提供每种性别的平均年龄。您需要在投影之前进行分组。

    [
{
"$group": {
"_id": "$gender",
"avrg": {
"$avg": "$age"
}
}
},
{
"$project": {
"gender": "$_id",
"avg": "$avrg",
"_id": 0
}
}
]

这是生成上述内容的 C# 测试程序:

using MongoDB.Entities;
using MongoDB.Entities.Core;
using System;
using System.Linq;

namespace StackOverflow
{
public class Person : Entity
{
public string Name { get; set; }
public string Gender { get; set; }
public int Age { get; set; }
}

public class Program
{
private static void Main(string[] args)
{
new DB("test", "localhost");

(new[] {
new Person{ Name = "one", Gender = "M", Age = 30},
new Person{ Name = "two", Gender = "M", Age = 30},
new Person{ Name = "three", Gender = "F", Age = 40},
new Person{ Name = "four", Gender = "F", Age = 40},
}).Save();

var res = DB.Queryable<Person>()
.GroupBy(p => p.Gender)
.Select(g => new
{
gender = g.Key,
avg = g.Average(p => p.Age)
})
.ToArray();

foreach (var r in res)
{
Console.WriteLine($"Gender: {r.gender} Average: {r.avg}");
}

Console.ReadKey();
}
}
}

关于python - MongoDB 分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58960246/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com