【发布时间】:2019-08-12 21:55:57
【问题描述】:
我目前正在制作一个成就系统并尝试将其保存在两个集合中。 一个包含名称和 ID 的集合, 以及与用户及其进度的其他集合。
我一直在研究 Aggregation 和 $lookup,并取得了一些进展,但我不确定需要做什么才能获得我想要的输出。
如果用户存在于成就中,则通过集合获取进度值及其用户ID,如果不存在,则将进度值设为0。
这会不会是某种加入,例如 Mysql?,这在 MongoDB 中会如何?
变量userid = 33;
尝试:
db.getCollection('achievements').aggregate([
{
$lookup:
{
from: "achievement_users",
localField: "id",
foreignField: "id",
as: "inventory_docs"
}
}
])
成就架构:
{
"name" : "testing",
"id" : 1,
"max" : 12,
},
{
"name" : "testing2",
"id" : 2,
"max" : 12,
}
成就用户:
{
"userid" : 33,
"id" : 1,
progress: 1,
},
{
"userid" : 446,
"id" : 1,
progress: 1,
}
期望的输出:
{
name: "testing",
id: 1,
userid: 33,
progress: 1,
max : 12,
},
{
name: "testing2",
id: 2,
progress: 0,
max : 12,
},
编辑:
我需要用户已完成和未完成的所有成就(未完成 = 进度 = 0)。
可能是用户没有完成的成就。我也希望它们列出来,但进度值为 0。
更新 2: 还需要它来给我结果,而在成就用户中没有与该特定用户 ID 匹配的情况。
【问题讨论】:
标签: javascript mongodb mongoose aggregation-framework schema