簡體   English   中英

加入/查找mongoose模式的agregation

[英]Join/lookup agregation on mongoose schema

我目前正在制作一個成就系統並嘗試將其保存在兩個系列中。 一個包含名稱和ID的集合,以及包含用戶及其進度的其他集合。

我一直在關注聚合,在$ 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,

},

編輯:

我需要用戶所做的所有成就,而不是已經完成(沒有完成= progress = 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進行最后清理

您可以使用以下聚合

db.achievement_users.aggregate([
  { "$match": { "userid": 33 }},
  { "$lookup": {
    "from": "achievement",
    "let": { "id": "$id", "progress": "$progress", "userid": "$userid" },
    "pipeline": [
      { "$addFields": {
        "progress": { "$cond": [{ "$eq": ["$id", "$$id"] }, "$$progress", 0] },
        "userid": "$$userid"
      }}
    ],
    "as": "inventory_docs"
  }},
  { "$unwind": "$inventory_docs" },
  { "$replaceRoot": { "newRoot": "$inventory_docs" }}
])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM