mongodb多表查询


db.ClassMembers.insertMany([
{
"ClassID":"CL0001",
"StudentID":"S000001",
"DateFrom":"2015-09-01"
},
{
"ClassID":"CL0002",
"StudentID":"S000002",
"DateFrom":"2015-09-01"
}
]);
db.Scores.insertMany([
{
"StudentID":"S000001",
"TestID":"T000001",
"Scores":[{
"Course":"Chinese",
"Score":80
},{
"Course":"Maths",
"Score":70
},{
"Course":"English",
"Score":75
}]
},
{
"StudentID":"S000002",
"TestID":"T000001",
"Scores":[{
"Course":"Chinese",
"Score":70
},{
"Course":"Maths",
"Score":80
},{
"Course":"English",
"Score":82
}]
}
]);
db.ClassMembers.aggregate([
{
$match: {ClassID: 'CL0001'}
},
{
$lookup:
{
from: "Scores",
localField: "StudentID",
foreignField: "StudentID",
as: "ScoresDocs"
}
},
{ $match : { "ScoresDocs.TestID" : 'T000001' }},
{ $project: { _id: 0, ClassID: 1, ScoresDocs: 1}},
{ $unwind: '$ScoresDocs'},
{ $unwind: '$ScoresDocs.Scores'},
{ $match: {'ScoresDocs.Scores.Course':'Chinese'}}

])

//最后一步

将数据从对象列取出来地址:https://docs.mongodb.com/master/reference/operator/aggregation/replaceRoot/#pipe._S_replaceRoot


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM