簡體   English   中英

從集合中選擇on子句,從集合b的JOIN中選擇

[英]Select from collection a on clause from JOIN on collection b

我有兩個收藏: gamesquestions
game架構:

{ 
  _id: ObjectId, 
  status: 'played',
  questions: 
     [ 
       { questionId: ObjectId(questions._id) } // ref to questions collection by _id field
     ] 
 }

questions模式:

{
  _id: ObjectId(),
  text: foobar
}

游戲可能具有兩種狀態:“活動”和“已玩”。
我的目標是獲得與狀態為“玩過”的游戲相關的所有“玩過的”問題,方式,問題。

我試圖對games集合進行查詢,試圖對questions進行查詢,但沒有一個起作用。

他們之中有一些是:

db.games.aggregate([
     {$match: {status: {$ne: 'played'}}}, 
     {
         $lookup: 
           {
            from: 'questions', 
            localField: 'questions.questionId', 
            foreignField: '_id', 
            as: 'game_questions'
         }
      }, 
    {$project: {game_questions: 1}}, 
    {$unwind: {path: '$game_questions', preserveNullAndEmptyArrays: false}}
   ])

要么

db.questions.aggregate([
     { $project: {text: 1}}, 
     { $lookup: {
        from: 'games', 
        pipeline: [
           { $match: {status:'played' }}, 
           { $project: { status: 1 }}
        ], 
        as: 'game_data' 
      }}
])

底線 :提出請求后,我想獲得一個包含問題的列表,其中游戲狀態為“玩過”。

您可以將$unwind$replaceRoot$lookup階段中找到的數據$replaceRoot使用

db.games.aggregate([
  { "$match": { "status": "played" }},
  { "$lookup": {
    "from": "questions",
    "let": { "questions": "$questions.questionId" },
    "pipeline": [
      { "$match": { "$expr": { "$in": ["$_id", "$$questions"] }}}
    ],
    "as": "game_data"
  }},
  { "$unwind": "$game_data" },
  { "$replaceRoot": { "newRoot": "$game_data" }}
])

要么

db.games.aggregate([
  { "$match": { "status": "played" }}, 
  { "$lookup": {    
    "from": "questions", 
    "localField": "questions.questionId", 
    "foreignField": "_id", 
    "as": "game_data"
  }}, 
  { "$unwind": "$game_data" },
  { "$replaceRoot": { "newRoot": "$game_data" }}
])

暫無
暫無

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

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