更新时间:2023-02-05 14:32:10
您需要先展开business_opportunities,然后再将它们与正则表达式匹配.以下是更新后的代码.
You need to unwind the business_opportunities before matching them with regular expression. Below is the updated code.
static async findRelatedTags(opts, params) {
assert.object(params, 'params')
assert.string(params.tag, 'params.tag')
assert.number(params.limit, 'params.limit')
assert.object(opts, 'opts')
assert.object(opts.mongo_db, 'opts.mongo_db')
const { mongo_db: db } = opts
const query = [
{ $unwind : "$comments" },
{
$match: {
business_opportunities: { '$regex': '^'+params.tag+'', $options: 'i' }
}
},
{ "$group": {
"_id": "$comments"
}
}
]
const cursor = db.collection('business_opportunities').aggregate([
...query
]).limit(params.limit)
var agg_results = cursor.toArray()
return agg_results.map(obj => obj._id)
}
MongoDB 聚合将为您提供这样匹配的 business_opportunities
MongoDB aggregation will give you the matched business_opportunities like this
[{
"_id" : "accounting"
},
{
"_id" : "app design"
},
{
"_id" : "aws"
}]
为了将其转换为 ["accounting", "app design", "aws"] 我在上面的示例中添加了 agg_results.map(obj => obj._id)
.
To convert it to ["accounting", "app design", "aws"] I have added agg_results.map(obj => obj._id)
in example above.
除了在您的代码中正则表达式搜索区分大小写,所以我使用了 { '$regex': '^'+params.tag+'', $options: 'i' }
使其不区分大小写,如果不需要,请删除 $options.
Except that in your code regex search is Case Sensitive so I have used { '$regex': '^'+params.tag+'', $options: 'i' }
to make it Case Insensitive, remove $options if you don't need it.