共計 1724 個字符,預計需要花費 5 分鐘才能閱讀完成。
自動寫代碼機器人,免費開通
這篇文章主要介紹 mongodb 如何實現同庫聯表查詢方法,文中介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們一定要看完!
注意:這里只對同庫聯表查詢做介紹,跨庫聯表查詢可能在之后也會介紹(因為公司架構變動,之后可能會聯表查詢)
我用到的聯表查詢有兩種,一種是 mongoose 的 populate,一種是 $lookup
一、populate
populate 是使用外鍵關聯子表
例如現在有一張訂單表結構(動態外鍵):
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 }, // 訂單的狀態:1 完成 2 未完成 3 失效
})
用戶表:
var userSchema = new mongoose.Schema({
phone: String,
status: String,
createdAt: Date,
updatedAt: Date
})
現在我想根據查詢 order 表,并返回對應用戶 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, // 訂單的狀態:1 完成 2 未完成 3 失效
// }
});
這里 order 表的 uid 指向了 user 表的_id 字段,當然也可以在新建表的時候定義外鍵,這里就不細說了
二、$lookup
lookup 就是使用 aggregate 的 $lookup 屬性,直接上官網例子非常好懂
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 以上貌似可以轉,沒試過)
以上是“mongodb 如何實現同庫聯表查詢方法”這篇文章的所有內容,感謝各位的閱讀!希望分享的內容對大家有幫助,更多相關知識,歡迎關注丸趣 TV 行業資訊頻道!
向 AI 問一下細節