Mongo数据两表关联创建视图示例
表tblCard:
{"cNo":"11","oRDate":ISODate("2017-08-01T00:00:00.000+0800")}
{"cNo":"12","oRDate":ISODate("2017-07-01T00:00:00.000+0800")}
{"cNo":"13","oRDate":ISODate("2017-09-01T00:00:00.000+0800")}
表temp:
{
"SIM" : "11"
}
{
"SIM" : "12"
}
{
"SIM" : "13"
}
需求:关联temp中SIM与tblCard中cNo,并输出SIM,oRDate
解决:
db.runCommand( { create: "viewORDate", viewOn: "temp", pipeline: [{ $lookup: { from: "tblCard", localField: "SIM", foreignField: "cNo",as:"vDoc" } },
{ $project: { "SIM": 1, "oRDate": "$vDoc.oRDate" } },{ $unwind : "$oRDate" }
] } )
其中: $lookup关联表、 $project过滤字段、$unwind循环取数组内容
db.viewORDate.find()的结果如下:
{
"SIM" : "11",ISODate("2017-08-01T00:00:00.000+0800")
}
{
"SIM" : "12",ISODate("2017-07-01T00:00:00.000+0800")
}
{
"SIM" : "13",ISODate("2017-09-01T00:00:00.000+0800")
}