[英]How to do joint table query in mongo db?
我對 mongodb 很陌生,過去我使用 mysql 進行數據庫查詢。
現在我有 2 個 mongo 集合:
+--------------+--------------+ | id | name | +--------------+--------------+ | 1 | good name | +--------------+--------------+ | 2 | bad name | +--------------+--------------+
+--------------+---------------+-------------------+ | id | companyId | name | +--------------+---------------+-------------------+ | 1 | 1 | bad position | +--------------+---------------+-------------------+ | 2 | 2 | good position | +--------------+---------------+-------------------+
現在我需要允許通過模糊匹配名稱(公司或職位名稱)來搜索職位。 例如,如果我按名稱“good”搜索,結果應該是 2 個位置。 因為對於位置 1,它的相關公司名稱包含“good”,而對於位置 2,它自己的名稱包含“good”。
那么我應該如何安排aggregation pipelines
來實現這一目標?
我嘗試了以下操作,但不起作用:
const lookup = {
from: "companies",
localField: "companyId",
foreignField: "_id",
as: "companies"
};
const match = {
$or: [
{
name: { $regex: companyOrPositionName }
},
{
"companies": { name: { $regex: companyOrPositionName } }
}
]
};
return await position.aggregate([{ $lookup: lookup }, { $match: match }]);
任何人都可以幫忙嗎? 提前致謝!
您可以嘗試以下聚合
position.aggregate([
{ "$lookup": {
"from": "companies",
"let": { "companyId": "$_id" },
"pipeline": [
{ "$match": { "$expr": { "$eq": [ "$_id", "$$companyId" ] } } },
{ "$project": { "name": 1 }}
],
"as": "companyName"
}},
{ "$unwind": "$companyName" },
{ "$match": {
"$or": [
{ "name": { "$regex": "good" }},
{ "companyName.name": { "$regex": "good" }}
]
}}
])
或者使用簡單的find
查詢
const companies = await Companies.find({ "name": { "$regex": "good" }})
const ids = companies.map(company => company._id)
position.find({
"$or": [
{ "companyId": { "$in": ids }},
{ "name": { "$regex": "good" }}
]
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.