我正在尝试使用以下管道计算出生在特定年份的用户数量。
{"$group": {"_id": "$birthdayYear", "count": {"$sum": 1}}}
但我得到的是以下所有年份总和,并且Mongo没有$count
功能,所以我该怎样做才能根据他们的年份对用户数量进行分组出生?
示例文档
{
"_id" : "LrN2tAK4rtyhsYFbr",
"firstName" : "abc",
"lastName" : "",
"birthdayDay" : 5,
"birthdayMonth" : 8,
"birthdayYear" : 1984,
}
/ * 1 * /
{
"_id" : "birthDayYear",
"count" : 5550.0
}
答案 0 :(得分:0)
我已将2个文档插入用户集合
db.users.insert({ "_id" : "LrN2tAK4rtyhsYFbs", "firstName" : "test", "lastName" : "1", "birthdayDay" : 5, "birthdayMonth" : 8, "birthdayYear" : 1984})
db.users.insert({ "_id" : "LrN2tAK4rtyhsYFbr", "firstName" : "test", "lastName" : "2", "birthdayDay" : 6, "birthdayMonth" : 9, "birthdayYear" : 1984})
运行以下查询
db.users.aggregate([{$group: {"_id": "$birthdayYear", count: {$sum:1}} }])
得到了结果
{ "_id" : 1984, "count" : 2 }
答案 1 :(得分:0)
请检查汇总语句的语法 - 我相信下面会显示所需的结果:
db.tstso1.aggregate([{$group : {_id : "$birthdayYear", count: { $sum: 1 }}}])
结果:
{ "_id" : 1986, "count" : 2 }
{ "_id" : 1985, "count" : 3 }
{ "_id" : 1984, "count" : 6 }
文件:
see.pretty();
{
"_id" : "LrN2tAK4rtyhsYFbr",
"firstName" : "abc",
"lastName" : "",
"birthdayDay" : 5,
"birthdayMonth" : 8,
"birthdayYear" : 1984
}
{
"_id" : "2",
"firstName" : "abc",
"lastName" : "",
"birthdayDay" : 5,
"birthdayMonth" : 8,
"birthdayYear" : 1984
}
{
"_id" : "3",
"firstName" : "abc",
"lastName" : "",
"birthdayDay" : 5,
"birthdayMonth" : 8,
"birthdayYear" : 1984
}
{
"_id" : "4",
"firstName" : "abc",
"lastName" : "",
"birthdayDay" : 5,
"birthdayMonth" : 8,
"birthdayYear" : 1984
}
{
"_id" : "6",
"firstName" : "abc",
"lastName" : "",
"birthdayDay" : 5,
"birthdayMonth" : 8,
"birthdayYear" : 1984
}
{
"_id" : "7",
"firstName" : "abc",
"lastName" : "",
"birthdayDay" : 5,
"birthdayMonth" : 8,
"birthdayYear" : 1984
}
{
"_id" : "12",
"firstName" : "abc",
"lastName" : "",
"birthdayDay" : 5,
"birthdayMonth" : 8,
"birthdayYear" : 1985
}
{
"_id" : "13",
"firstName" : "abc",
"lastName" : "",
"birthdayDay" : 5,
"birthdayMonth" : 8,
"birthdayYear" : 1986
}
{
"_id" : "14",
"firstName" : "abc",
"lastName" : "",
"birthdayDay" : 5,
"birthdayMonth" : 8,
"birthdayYear" : 1985
}
{
"_id" : "16",
"firstName" : "abc",
"lastName" : "",
"birthdayDay" : 5,
"birthdayMonth" : 8,
"birthdayYear" : 1986
}
{
"_id" : "17",
"firstName" : "abc",
"lastName" : "",
"birthdayDay" : 5,
"birthdayMonth" : 8,
"birthdayYear" : 1985
}