MongoDB聚合组
我在mongodb中存储了如下文档:MongoDB聚合组,mongodb,mongodb-query,aggregation-framework,Mongodb,Mongodb Query,Aggregation Framework,我在mongodb中存储了如下文档: { _id: ObjectId("abc"), teams: [{ _id: ObjectId("aaa"), points: 10 }, { _id: ObjectId("bbb"), points: 20 }], players: [{ hints: 2, team: ObjectId("aaa") }, { hints: 3, team: ObjectId("bbb
{
_id: ObjectId("abc"),
teams: [{
_id: ObjectId("aaa"),
points: 10
}, {
_id: ObjectId("bbb"),
points: 20
}],
players: [{
hints: 2,
team: ObjectId("aaa")
}, {
hints: 3,
team: ObjectId("bbb")
}]
}
给定一组文档,我想提取团队积分及其球员提示的总和。基本上,我想得到如下结果:
[{
team: aaa,
points: 10,
hints: 2
}, {
team: bbb,
points: 20,
hints: 3
}]
其中,points是团队在每个文档中获得的“点数”的总和,“提示”是其参与者获得的提示的总和。
我可以通过两个查询实现这一点:
db.data.aggregate([ {$unwind: { "$players" },
{$group: { _id: "$players.team", hints: { $sum: "$player.hints" } } }])
有没有办法只用一个查询就可以做到这一点?您的两个查询是正确的,您可以使用它在一个查询中应用它们。在这之后,您需要对数组进行压缩,然后根据团队id展开和分组 问题是:
db.collection.aggregate([
{
$facet: {
"points": [
{
$unwind: "$teams"
},
{
$group: {
_id: "$teams._id",
points: {
$sum: "$teams.points"
}
}
},
],
"hints": [
{
$unwind: "$players"
},
{
$group: {
_id: "$players.team",
hints: {
$sum: "$players.hints"
}
}
}
]
}
},
{
$project: {
merged: {
$concatArrays: [
"$points",
"$hints"
]
}
}
},
{
$unwind: "$merged"
},
{
$group: {
_id: "$merged._id",
points: {
$max: "$merged.points"
},
hints: {
$max: "$merged.hints"
}
}
}
])
它将输出您想要的内容
db.data.aggregate([ {$unwind: { "$teams" },
{$group: { _id: "$teams._id", points: { $sum: "$teams.points" } } }])
[{ team: aaa, points: 10 },{ team: bbb, points: 20 }]
db.collection.aggregate([
{
$facet: {
"points": [
{
$unwind: "$teams"
},
{
$group: {
_id: "$teams._id",
points: {
$sum: "$teams.points"
}
}
},
],
"hints": [
{
$unwind: "$players"
},
{
$group: {
_id: "$players.team",
hints: {
$sum: "$players.hints"
}
}
}
]
}
},
{
$project: {
merged: {
$concatArrays: [
"$points",
"$hints"
]
}
}
},
{
$unwind: "$merged"
},
{
$group: {
_id: "$merged._id",
points: {
$max: "$merged.points"
},
hints: {
$max: "$merged.hints"
}
}
}
])