显示来自两个集合的结果并对该结果数据应用过滤器

时间:2017-01-31 08:46:06

标签: mongodb meteor

我有一种情况需要显示来自两个集合的组合数据。显示结果数据后,我想对此结果数据应用过滤器。

有人可以提出方法或者可以展示这个流程的例子吗? 这是我的数据输出

用户

{ 
    "_id" : "a6s54fas46456",
    "studentId" : "qYt5yHiZfbGrvXWak",
    "name" : "name1"
}
{ 
    "_id" : "asdf46asd4f", 
    "studentId" : "e2r4nTRiZZRsX6Xgu",
    "name" : "name2"
}
{ 
    "_id" : "asdf463443asd4f", 
    "studentId" : null,
    "name" : "name3"
}
{ 
    "_id" : "a6s54fas42346456", 
    "studentId" : "qYt5yHiZfbGrvXWak",
    "name" : "name4"
}
{ 
    "_id" : "asdf46asd6542344f", 
    "studentId" : null,
    "name" : "name3"
}

学生

{ 
    "_id" : "e2r4nTRiZZRsX6Xgu", 
    "studentName" : "student2"
}
{ 
    "_id" : "qYt5yHiZfbGrvXWak", 
    "studentName" : "student1"
}

输出

{
UserId: a6s54fas46456
StudentId : "qYt5yHiZfbGrvXWak"
"name" : "name1"
"studentName" : "student1"
}
{
UserId: asdf46asd4f
StudentId : "e2r4nTRiZZRsX6Xgu"
"name" : "name2"
"studentName" : "student1"
}
{
UserId: asdf463443asd4f
StudentId : null
"name" : "name3"
"studentName" : null
}
{
UserId: a6s54fas42346456
StudentId : "qYt5yHiZfbGrvXWak"
"name" : "name4"
"studentName" : "student1"
}
{
UserId: asdf46asd6542344f
StudentId : null
"name" : "name3"
"studentName" : null
}

由于

1 个答案:

答案 0 :(得分:1)

要从两个集合中获取数据,您应该使用$lookup$unwind preserveNullAndEmptyArrays:true:true

db.users.aggregate([
    {$lookup:{from:"students", localField:"studentId", foreignField:"_id", as:"student"}},
    {$unwind:{path:"$student",preserveNullAndEmptyArrays:true}},
    {$project:{
        "UserId":"$_id",
        "StudentId" : "$student._id",
        "name" : 1,
        "studentName" : "$student.studentName"
        }
    }
])