简体   繁体   中英

Select from collection a on clause from JOIN on collection b

I have two collections: games and questions
game schema:

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

questions schema:

{
  _id: ObjectId(),
  text: foobar
}

Game could have two statuses: 'active' and 'played'.
My goal is to get all 'played' questions, means, questions, associated with games with status 'played'.

I've tried to make queries on games collection, tried to make queries on questions but none of them worked.

Some of them are:

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

Or

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

Bottom line : After the request I'd like to get a list with questions, where game status is 'played'.

You can use $unwind and $replaceRoot with the data found in $lookup stage

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

Or

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM