[英]How to do joint table query in mongo db?
I'm quite new with mongodb, in the past I worked with mysql for database queries.我对 mongodb 很陌生,过去我使用 mysql 进行数据库查询。
Now I have 2 mongo collections:现在我有 2 个 mongo 集合:
+--------------+--------------+ | id | name | +--------------+--------------+ | 1 | good name | +--------------+--------------+ | 2 | bad name | +--------------+--------------+
+--------------+---------------+-------------------+ | id | companyId | name | +--------------+---------------+-------------------+ | 1 | 1 | bad position | +--------------+---------------+-------------------+ | 2 | 2 | good position | +--------------+---------------+-------------------+
Now I need to allow searching positions by fuzzy matching the name, either company or position name.现在我需要允许通过模糊匹配名称(公司或职位名称)来搜索职位。 For example, if I search by name "good", the result should be the 2 positions.
例如,如果我按名称“good”搜索,结果应该是 2 个位置。 Because for the position 1, it's correlated company's name contains "good", and for the position 2, it's own name contains "good".
因为对于位置 1,它的相关公司名称包含“good”,而对于位置 2,它自己的名称包含“good”。
So how should I arrange the aggregation pipelines
to achieve that?那么我应该如何安排
aggregation pipelines
来实现这一目标?
I tried with the following but it doesn't work:我尝试了以下操作,但不起作用:
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 }]);
Can anyone help?任何人都可以帮忙吗? Thanks in advance!
提前致谢!
You can try below aggregation您可以尝试以下聚合
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" }}
]
}}
])
or either with simple find
queries或者使用简单的
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.