MongoDB从基础添加到加入集合字段 [英] MongoDB add to joining collection field from base one
问题描述
我有两个收藏:
带有架构的游戏:
_id: ObjectId('gameId'),
questions: [
{
position: 1,
question_id: ObjectId('baz')
},
{
position: 2,
question_id: ObjectId('ban')
},
]
架构问题:
_id: ObjectId('baz'),
text: 'FooBar'
现在我想将问题加入到游戏中,并添加到 question_position
的每个问题记录值.
And now I'd like to join questions to games with adding to each question record value of question_position
.
所以,我有这样的查询:
So, I have query like this:
db.games.aggregate([
{
$lookup: {
from: 'questions',
localField: 'questions.question_id',
foreignField: '_id',
as: 'question_data',
},
}])
返回所有必需的信息,并根据问题数组正确连接,
Which return me all required info, with correct join according to questions array,
_id: ObjectId('gameId'),
questions: [
{
position: 1,
question_id: ObjectId('baz')
},
{
position: 2,
question_id: ObjectId('ban')
}
],
question_data: [
{
_id: ObjectId('baz'),
text: 'FooBar',
},
{
_id: ObjectId('ban'),
text: 'FooBar2',
}
]
但我完全不知道如何根据游戏将其位置添加到连接问题中.看起来像这样:
but I'm totally can't figure out how to add into joined questions it's position according to game. To look it like this:
_id: ObjectId('gameId'),
questions: [
{
position: 1,
question_id: ObjectId('baz')
},
{
position: 2,
question_id: ObjectId('ban')
}
],
question_data: [
{
_id: ObjectId('baz'),
text: 'FooBar',
position: 1,
},
{
_id: ObjectId('ban'),
text: 'FooBar2',
position: 2,
}
]
我已经尝试使用 $unwind
作为游戏集合中的问题数组,在 aggregation
中使用 $project
玩了一下,但仍然没有结果.
I've tried with $unwind
for question array in game collection, played a little with $project
in aggregation
but still no result.
所以,我的问题是,如何将基础集合中的字段添加到另一个集合中的连接数据中
So, my question is, how to add field from base collection to joined data from another collection
推荐答案
你需要先$unwind
questions
数组,然后需要应用 $lookup
最后使用 $group
回滚再次进入数组.
You need to first $unwind
the questions
array and then need to apply $lookup
and finally use $group
to rollback again into the array.
db.games.aggregate([
{ "$unwind": "$questions" },
{ "$lookup": {
"from": "questions",
"localField": "questions.question_id",
"foreignField": "_id",
"as": "question_data"
}},
{ "$unwind": "$question_data" },
{ "$addFields": {
"question_data.position": "$questions.position",
"question_data.question_id": "$questions.question_id"
}},
{ "$group": {
"_id": "$_id",
"questions": { "$push": "$questions" },
"question_data": { "$push": "$question_data" }
}}
])
这篇关于MongoDB从基础添加到加入集合字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!