這里只對同庫聯(lián)表查詢做介紹乒躺,跨庫聯(lián)表查詢可能在之后也會介紹(因為公司架構(gòu)變動扬霜,之后可能會聯(lián)表查詢)
我用到的聯(lián)表查詢有兩種抹锄,一種是mongoose的populate,一種是$lookup
populate
populate是使用外鍵關(guān)聯(lián)子表
例如現(xiàn)在有一張訂單表結(jié)構(gòu)(動態(tài)外鍵):
var orderSchema = new mongoose.Schema({
uid: { type: String, required: true }, // 用戶id
amount: { type: Number, required: true },
oType: { type: Number, required: true }, // 訂單類型
status: { type: Number, required: true }, // 訂單的狀態(tài):1完成 2未完成 3失效
})
用戶表:
var userSchema = new mongoose.Schema({
phone: String,
status: String,
createdAt: Date,
updatedAt: Date
})
現(xiàn)在我想根據(jù)查詢order表雌续,并返回對應(yīng)用戶phone字段
order.find().populate({path: 'uid', model: User, select: '_id real_name phone bankcard'}).exec(function(err, order) {
// order: {
// uid: {
// phone: '15626202254',
// status: "expand",
// createdAt: Date,
// updatedAt: Date
// },
// amount: 5000,
// oType: 2, // 訂單類型
// status: 1, // 訂單的狀態(tài):1完成 2未完成 3失效
// }
});
這里order表的uid指向了user表的_id字段,當(dāng)然也可以在新建表的時候定義外鍵胯杭,這里就不細說了
$lookup
lookup就是使用aggregate的$lookup屬性驯杜,直接上官網(wǎng)例子非常好懂
orders表
{ "_id" : 1, "item" : "abc", "price" : 12, "quantity" : 2 }
{ "_id" : 2, "item" : "jkl", "price" : 20, "quantity" : 1 }
{ "_id" : 3 }
inventory表
{ "_id" : 1, "sku" : "abc", description: "product 1", "instock" : 120 }
{ "_id" : 2, "sku" : "def", description: "product 2", "instock" : 80 }
{ "_id" : 3, "sku" : "ijk", description: "product 3", "instock" : 60 }
{ "_id" : 4, "sku" : "jkl", description: "product 4", "instock" : 70 }
{ "_id" : 5, "sku": null, description: "Incomplete" }
{ "_id" : 6 }
db.orders.aggregate([
{
$lookup:
{
from: "inventory",
localField: "item",
foreignField: "sku",
as: "inventory_docs"
}
}
])
就是使用order的item字段作為inventory表的查詢條件{sku: item},并賦值給inventory_docs字段做个,但值得注意的是兩個字段的類型必須一樣(3.5以上貌似可以轉(zhuǎn)鸽心,沒試過)