总结第二个集合中的要点,并将其放在第一个集合中。
提供两项收藏品:
a:
{
_id: 123323525245,
token: "token_1",
points: 0
},
{
_id: 3454545334
token: "token_2"
points: 0
}
b:
_id: 1324454:
lines: [
{
token: "token_1",
points: 20
},
{
token: "token_1",
points: 10
},
{
token: "token_2",
points: 12
}
]我想通过标记总结集合b中的所有要点,并将其放入预期的集合中:
a:
{
_id: 123323525245,
token: "token_1",
points: 30
},
{
_id: 3454545334
token: "token_2"
points: 12
}我应该使用什么查询?
发布于 2022-11-21 08:44:40
首先展开集合b,然后按令牌分组。
db.b.aggregate([
{
"$unwind": "$lines"
},
{
"$group": {
"_id": "$lines.token",
"points": {
"$sum": "$lines.points"
}
}
},
{
"$lookup": {
"from": "a",
"localField": "_id",
"foreignField": "token",
"as": "docs"
}
},
{
"$project": {
"_id": {
"$first": "$docs._id"
},
"points": "$points",
"token": "$_id"
}
}
])https://stackoverflow.com/questions/74515755
复制相似问题