我有两个收藏集:games
和questions
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'
}}
])
底线: 提出请求后,我想获得一个包含问题的列表,其中游戏状态为“玩过”。
答案 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" }}
])