Vuk*_*kez 6 mongoose mongodb node.js mongodb-query
I am trying to find() all docs with LIKE 'query.name' in concatenated fields instead of using $or to search in separated ones.
SQL query would be:
SELECT * FROM table WHERE column.name + ' ' + column.surname LIKE query.name
Run Code Online (Sandbox Code Playgroud)
This is the current code:
Model.find()
.and([
{
$or: [
{ name: new RegExp(req.query.name, 'i') },
{ surname: new RegExp(req.query.name, 'i') }
]
},
{
$or: [
{ workPlace: new RegExp(req.query.place, 'i') },
{ location: new RegExp(req.query.place, 'i') }
]
}
])
Run Code Online (Sandbox Code Playgroud)
这可以在两阶段聚合查询中实现:其想法是$concat
在第一阶段使用连接名称和位置字段作为单独的过滤器属性$addFields
,然后在下一阶段使用$match
and进行搜索。$regex
例子:
db.collection.aggregate([
{
$addFields: {
nameFilter: {
$concat: ["$name", " ", "$surname"],
},
locationFilter: {
$concat: ["$workplace", " ", "$location"],
},
},
},
{
$match: {
nameFilter: {
$regex: req.query.name,
$options: "i",
},
locationFilter: {
$regex: req.query.place,
$options: "i",
},
},
},
]);
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
2097 次 |
最近记录: |