我想通过在MongoDB上使用$ lookup和$ match来获取带有外键的文档。
有一个存储Job文档的“Jobs”集合。在Job文档中有两个字段用作foreing键“creatorParent”和“Children”。 CreatorParent是“Users”集合的外键,Children数组包含用户子节点的id。
当我列出整个作业时,我想从“Users”集合中检索CreatorParent ID和ChildrenID的详细信息。我想用ParentDetail和ChildDetail编写“Job”文档。我不想为此编写自定义方法。是否可以使用MongoDB查询来处理它?</ p>
顺便说一下,我是MongoDB的初学者,所以应该在Children和CreatorParent上存储所需的详细信息,而不是存储ObjectId?
用户文档:
KeyboardFocusChangedEventArgs
工作
true
答案 0 :(得分:0)
如果我理解正确的话。使用MongoDB 3.4的$ addFields和$ lookup聚合步骤可以实现类似的解决方案。
Mongo聚合:
[
{
$addFields: {
"job":"$$ROOT"
}
},
{
$unwind: {
path : "$children"
}
},
{
$lookup: {
"from" : "users",
"localField" : "creatorParent",
"foreignField" : "_id",
"as" : "creatorParent"
}
},
{
$lookup: {
"from" : "users",
"localField" : "children",
"foreignField" : "_id",
"as" : "children"
}
},
{
$group: {
"_id": "$_id",
"job": { "$first": "$job" },
"creatorParent" : { "$first" : "$creatorParent" },
"children": { "$addToSet": { $arrayElemAt: [ "$children", 0 ] } }
}
}
]
输出如下所示:
{ "_id" : ObjectId("58da9cb6340c630315348114"),
"job" : {
"_id" : ObjectId("58da9cb6340c630315348114"),
"name" : "Developer",
"creatorParent" : ObjectId("58da9c79340c630315348113"),
"children" : [
ObjectId("58da9c6d340c630315348112"),
ObjectId("58da9c5f340c630315348111")
],
"hourly_rate" : 12.0,
"additional_information" : "other infos"
},
"creatorParent" : [
{
"_id" : ObjectId("58da9c79340c630315348113"),
"name" : "The Boss",
"age" : 40.0
}
],
"children" : [
{
"_id" : ObjectId("58da9c5f340c630315348111"),
"name" : "James",
"age" : 28.0
},
{
"_id" : ObjectId("58da9c6d340c630315348112"),
"name" : "Andrew",
"age" : 26.0
}
]}
<强>更新强>
如果用最后一个$group
阶段代替:
{
"_id": "$_id",
"name": { "$first": "$name" },
"jobstatus": { "$first": "$jobstatus" },
"hourlyrate": { "$first":"$hourlyrate" },
"creatorparent" : { "$first" : "$creatorparent" },
"children": { "$addToSet": { $arrayElemAt: [ "$children", 0 ] } }
}
然后,您可以实现您想要的目标,但在此$group
阶段,您必须使用$first
表达式逐个指定每个作业字段。