Próbuję obliczyć średni wiek pogrupowany według płci. Oczekiwany wynik powinien być
{'_id': {'gender': 'M'},{'avg': '27.1}}
{'_id': {'gender': 'F'}},{'avg': '29.0}}
Oto mój kod poniżej
pipeline = [
{
"$project" : {
"_id" : {'gender':"$gender"},
"avg": {"$avg":"$age"},
}
},
{"$group" : {"_id":"$_id"}},
]
for doc in db.user.aggregate(pipeline):
print(doc)
W tej chwili wynik to:
{'_id': {'gender': 'M'}}
{'_id': {'gender': 'F'}}
Każda pomoc będzie mile widziana! Wiem, że to może być łatwe .....
1 odpowiedź
Poniższy schemat poda średni wiek dla każdej płci. musisz zgrupować przed rzutowaniem.
[
{
"$group": {
"_id": "$gender",
"avrg": {
"$avg": "$age"
}
}
},
{
"$project": {
"gender": "$_id",
"avg": "$avrg",
"_id": 0
}
}
]
Oto program testowy C #, który wygenerował powyższe:
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();
}
}
}
Podobne pytania
Nowe pytania
python
Python to wielozadaniowy, wielozadaniowy język programowania dynamicznie typowany. Został zaprojektowany tak, aby był szybki do nauczenia się, zrozumienia i użycia oraz wymuszania czystej i jednolitej składni. Należy pamiętać, że Python 2 oficjalnie nie jest obsługiwany od 01-01-2020. Mimo to, w przypadku pytań Pythona specyficznych dla wersji, dodaj znacznik [python-2.7] lub [python-3.x]. Korzystając z wariantu Pythona (np. Jython, PyPy) lub biblioteki (np. Pandas i NumPy), należy umieścić go w tagach.