一對(duì)多
先創(chuàng)建一張表countryCode
db.countryCode.insert([{code: 1}, {code: 20}, {code: 30}])
[圖片上傳失敗...(image-dae595-1512822343904)]
第二張表countryCodeLookup
,這張表顯示country的code和country的name 的對(duì)應(yīng)關(guān)系是一對(duì)多
db.countryCodeLookup.insert([{code: 1, name: "United States"}, {code: 20, name: "Egypt"},
{code: 1, name: "Foobar"}, {code: 30, name: "Greece"}])
[圖片上傳失敗...(image-fcefd8-1512822343904)]
$lookup、$project
下面通過 $lookup 操作符連接兩個(gè)集合遍蟋,其中 $project 會(huì)過濾屬性
db.countryCode.aggregate([
{ $lookup: {from: "countryCodeLookup", localField: "code", foreignField: "code", as: "countryName"} },
{ $project: {"code":1, "countryName.name":1, "_id":0} }
])
[圖片上傳失敗...(image-3ce4d3-1512822343904)]
$match
$match 會(huì)查詢連接后的表税灌,顯示符合條件的均函。
db.countryCode.aggregate([
{ $lookup: {from: "countryCodeLookup", localField: "code", foreignField: "code", as: "countryName"} },
{ $project: {"code":1, "countryName.name":1, "_id":0} },
{ $match:{"code":1.0}}
])
[圖片上傳失敗...(image-7499e7-1512822343904)]
一對(duì)一
$unwind
$unwind操作符會(huì)分解$lookup中的as數(shù)組,使之扁平化返回菱涤。
db.countryCode.aggregate([
{ $lookup: {from: "countryCodeLookup", localField: "code", foreignField: "code", as: "countryName"} },
{ $project: {"code":1, "countryName.name":1, "_id":0} },
{ $unwind: "$countryName"},
{ $match:{"code":1.0}}
])
[圖片上傳失敗...(image-fcc105-1512822343904)]
現(xiàn)在countryName是一個(gè)子文檔苞也,在project中設(shè)置把子文檔中的屬性拿出來,這里$project要在$unwind屬性后面粘秆。
db.countryCode.aggregate([
{ $lookup: {from: "countryCodeLookup", localField: "code", foreignField: "code", as: "countryName"} },
{ $unwind: "$countryName"},
{ $project: {"code":1, "name": "$countryName.name", "_id":0} }
])
[圖片上傳失敗...(image-185c94-1512822343905)]