2017-08-14 80 views
0

我很困惑,爲什麼下面不起作用。任何人都可以解釋一下嗎? 對於某些上下文:我的目標是將得分與調查數據庫的答案選項相關聯,答案存儲在單獨的問題集合中。問題集合包含一系列答案選項,這些答案選項有一個分數。MongoDB聚合管道匹配 - >查找 - >展開 - >匹配問題

運行此查詢:

db.answers.aggregate([ 
{ 
    $match: { 
     userId: "abc", 
     questionId: ObjectId("598be01d4efd70a81c1c5ad4") 
    } 
}, 
{ 
    $lookup: { 
     from: "questions", 
     localField: "questionId", 
     foreignField: "_id", 
     as: "question" 
    } 
}, 
{ 
    $unwind: "$question" 
}, 
{ 
    $unwind: "$question.options" 
}, 
{ 
    $unwind: "$answers" 
} 
]) 

我得到:

{ 
    "_id" : ObjectId("598e588e0c5e24452c9ee769"), 
    "userId" : "abc", 
    "questionId" : ObjectId("598be01d4efd70a81c1c5ad4"), 
    "answers" : { 
     "id" : 20 
    }, 
    "question" : { 
     "_id" : ObjectId("598be01d4efd70a81c1c5ad4"), 
     "options" : { 
      "id" : 10, 
      "score" : "12" 
     } 
    } 
} 
{ 
    "_id" : ObjectId("598e588e0c5e24452c9ee769"), 
    "userId" : "abc", 
    "questionId" : ObjectId("598be01d4efd70a81c1c5ad4"), 
    "answers" : { 
     "id" : 20 
    }, 
    "question" : { 
     "_id" : ObjectId("598be01d4efd70a81c1c5ad4"), 
     "options" : { 
      "id" : 20, 
      "score" : "4" 
     } 
    } 
} 

所有偉大的。如果我現在添加到原來的查詢是應該找到具有相同ID作爲答案(如questions.options.id == answers.id答案選項的比賽,事情並沒有工作,我期望

最後的管道是:

這將返回一個空的結果。但是,如果我從"$answers.id"改變$match的RHS到20,它返回預期score: 4。我什麼都試過了我能想到的,但不能讓它的工作,不能理解爲什麼它不起作用

回答

0

我能夠得到它具有以下管道工作:

{ 
    $match: { 
     userId: "abc", 
     questionId: ObjectId("598be01d4efd70a81c1c5ad4") 
    } 
}, 
{ 
    $lookup: { 
     from: "questions", 
     localField: "questionId", 
     foreignField: "_id", 
     as: "question" 
    } 
}, 
{ 
    $unwind: "$question" 
}, 
{ 
    $unwind: "$question.options" 
}, 
{ 
    $unwind: "$answers" 
}, 
{ 
    $addFields: { 
     areEqual: { $eq: [ "$question.options.id", "$answers.id" ] } 
    } 
}, 
{ 
    $match: { 
     areEqual: true 
    } 
}, 
{ 
    $project: { 
     _id: 0, 
     score: "$question.options.score" 
    } 
} 

我認爲它沒有用直接匹配工作的原因是questions.options.id實際上並沒有引用預期的領域其實......我需要使用$questions.options.id,它不會作爲$match的LHS工作,因此需要添加一個額外的輔助屬性。

相關問題