Mongoose aggregate 多表關聯查詢

2021-10-04 03:16:10 字數 1977 閱讀 8379

使用mongoose操作mongodb資料庫進行關聯查詢是一種比較常見的操作,操作方式有哪幾種呢?下面用乙個具體的案例來演示。

首先模擬一點資料,分別有 order 和 order_item 兩個集合:

order 集合裡的資料

order_item 集合裡的資料

假設要做這樣的乙個操作:

查詢 order_item 集合,找出商品名稱是酸奶的商品以及所對應的訂單的資訊,酸奶所對應的id為 "5e6f15faeb57cc45bde81312"

查詢方式一:

1. 在 order_item 中查出 order_id,然後通過order_id 查詢 order 集合,查出訂單的資訊。

定義 order 的 schema,匯出模型,檔名為 order.js

// 引入自定義的連線資料庫的檔案

var mongoose=require('./db.js');

// 定義訂單的schema

var orderschema=mongoose.schema();

module.exports=mongoose.model('order',orderschema,'order');

定義 order_item 的 schema ,匯出模型,檔名為 order_item.js

// 引入自定義的連線資料庫的檔案

var mongoose=require('./db.js');

// 定義訂單商品列表的schema

var orderitemschema=mongoose.schema();

module.exports=mongoose.model('orderitem',orderitemschema,'order_item');

在需要查詢的檔案裡引入兩個模型檔案,執行操作

var orderitemmodel = require('./model/order_item.js');

var ordermodel = require('./model/order.js');

orderitemmodel.find(, function (err, docs) , function (err, order) )

})

查詢方式二:

定義 order_item 的 schema ,匯出模型,檔名為 order_item.js

// 引入自定義的連線資料庫的檔案

var mongoose=require('./db.js');

// 定義訂單商品列表的schema

var orderitemschema=mongoose.schema();

module.exports=mongoose.model('orderitem',orderitemschema,'order_item');

在需要查詢的檔案裡引入定義的模型檔案,執行操作

// 引入mongoose方便獲取id

var mongoose = require('mongoose');

var orderitemmodel = require('./model/order_item.js');

orderitemmodel.aggregate([

}, }

], function (err, docs)

console.log(json.stringify(docs))

})

相比查詢方式一,第二種方式只需要定義乙個模型,寫法會更優雅一點,也是mongoose推薦的方式。

需要注意的是,在 mongoose 裡獲取 objectid,要用 mongoose.types.objectid 才能獲取的到。

多表關聯查詢

表別名 多個表之間存在同名的列,則必須使用表明來限制列的引用 內連線 自連線 內連線就是關聯的兩張或多張表中,根據關聯條件,顯示所有匹配的記錄,匹配不上的,不顯示 自連線,就是把一張表取兩個別名,當做兩張表來使用,自己和自己關聯。select columns list from table name...

JPA多表關聯查詢

作用 就是實現使用乙個實體類物件操作或者查詢多個表的資料。回顧 配置多表聯絡查詢必須有兩個步驟 1.在實體類裡面建立表與表之間的關係。2.配置關聯關係,jpa使用註解配置 需求 指定oid查詢客戶的資訊 公司資訊 同時也查詢關聯的聯絡人資訊 配置步驟 通過客戶找聯絡人,所以再customer實體類配...

ABAP 多表關聯 查詢

inner join 等值連線 只返回兩個表中聯結字段相等的行 left join 左聯接 返回包括左表中的所有記錄和右表中聯結字段相等的記錄 right join 右聯接 返回包括右表中的所有記錄和左表中聯結字段相等的記錄 inner join 語法 inner join 連線兩個資料表的用法 s...