javascript - Mongoose 模式中的加入/查找聚合

标签 javascript mongodb mongoose aggregation-framework schema

我目前正在制作一个成就系统,并试图将其保存在两个集合中。 一个包含名称和 ID 的集合, 以及其他包含用户及其进度的集合。

我一直在研究聚合和 $lookup,并取得了一些进展,但我不确定需要做什么才能获得我想要的输出。

如果用户存在于成就中,则获取进度值及其userid与集合,如果不存在,则将进度值设为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: 还需要它在 achievement_users 中没有匹配该特定用户 ID 的情况下给我结果。

最佳答案

如果您想执行类似于 LEFT JOIN 的操作,这里有一个解决方案:

db.test.aggregate([{
    $lookup: {
        from: "user",
        localField: "id",
        foreignField: "id",
        as: "inventory_docs"
    }
}, {
    $unwind: {path: "$inventory_docs", preserveNullAndEmptyArrays: true }
}, {
    $addFields: {
        userid: "$inventory_docs.userid",
        progress: {$cond: {if: "$inventory_docs.progress", then: "$inventory_docs.progress", else: 0 }},
    }
}, {
    $project: {
        inventory_docs: 0
    }
}])

$lookup 从连接的集合中创建一个数组

$unwind 拆分记录中的数组

$addFields随心所欲地提取你想要的字段

$cond 用 0 替换空进度

$project 进行最后的清理

关于javascript - Mongoose 模式中的加入/查找聚合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55290696/

相关文章:

javascript - 更改 JQuery 选项卡 slider 上的图像大小

javascript - JS中多次减去值

javascript - 字段的动态数量取决于另一个字段的值

mongodb - 用户评分模式 - 键/值数据库

node.js - 聚合查找中面临的问题。需要查找结果与定义的结构相同

javascript - MongoDB 查找和修改

node.js - 如何加入同步和异步世界?

javascript - jest-jasmine2 env.js 未处理的错误

javascript - 获取 JSON 对象的子键名称

javascript - Mongoose gridfs-stream 如何填充 fs.file 集合