从集合中选择on子句,从集合b的JOIN中选择

时间:2018-11-14 16:51:31

标签: mongodb mongoose mongodb-query aggregation-framework

我有两个收藏集: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' 
      }}
])

底线: 提出请求后,我想获得一个包含问题的列表,其中游戏状态为“玩过”。

1 个答案:

答案 0 :(得分:2)

您可以对在$unwind阶段找到的数据使用$replaceRoot$lookup

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" }}
])