更新时间:2023-01-29 18:39:09
是的,您可以使用聚合框架来做到这一点.它不会很漂亮,但是它仍然会比使用mapreduce更快.
Yes, you can do this with aggregation framework. It won't be pretty, but then it'll still be much faster than with mapreduce...
简而言之(输出的格式与您提供的格式不同,但内容相同):
Here it is in a nutshell (output a different format than what you give but same content):
> group1 = {
"$group" : {
"_id" : "$race",
"class" : {
"$push" : "$class"
},
"count" : {
"$sum" : 1
}
}
};
> unwind = { "$unwind" : "$class" };
> group2 = {
"$group" : {
"_id" : "$class",
"classCount" : {
"$sum" : 1
},
"races" : {
"$push" : {
"race" : "$_id",
"raceCount" : "$count"
}
}
}
};
> unwind2 = { "$unwind" : "$races" };
> group3 ={
"$group" : {
"_id" : 1,
"classes" : {
"$addToSet" : {
"class" : "$_id",
"classCount" : "$classCount"
}
},
"races" : {
"$addToSet" : "$races"
}
}
};
> db.races.aggregate(group1, unwind, group2, unwind2, group3);
{
"result" : [
{
"_id" : 1,
"classes" : [
{
"class" : "Fighter",
"classCount" : 1
},
{
"class" : "Hunter",
"classCount" : 3
},
{
"class" : "Rogue",
"classCount" : 1
}
],
"races" : [
{
"race" : "Naga",
"raceCount" : 2
},
{
"race" : "Halfling",
"raceCount" : 3
}
]
}
],
"ok" : 1
}