如何在mongodb中使用$ lookup和$ regex搜索 [英] how to work with $lookup and $regex search in mongodb
问题描述
var query = req.params.query;
const messages = await Message.aggregate([
{
$lookup: {
from: 'users',
localField: 'reference_id',
foreignField: '_id',
as: 'users'
}
},
{'text': {'$regex': `.*${query}.*`}}
])
$ lookup向我提供了正确的信息,但是$ regex无法正常工作当添加{'text':{'$ regex':.*${query}.*
}}告诉我,在$ lookup我有数据之后,参数必须是聚合管道运算符
$lookup is providing me right information but $regex is not properly working When add {'text': {'$regex': .*${query}.*
}} tells me Arguments must be aggregate pipeline operators after $lookup i have data
{
"response": {
"messages": [
{
"_id": "5e4a8e640b92852e110af62f",
"text": "Gsshha",
"reference_id": null,
"date": 1581944420262,
"users": [
{
"_id": "5e4a8d2d3952132a08ae5764",
"phone": "1111111111",
"first_name": "Test1",
"last_name": "Test1",
"timestamp": 1581944109860
}
]
},
{
"_id": "5e4ce3a4f55dd93292cbe149",
"unreads": [
"text": "Hi",
"reference_id": null,
"date": 1582097316013,
"users": [
{
"_id": "5e4a8d2d3952132a08ae5764",
"phone": "1111111111",
"first_name": "Test1",
"last_name": "Test1",
"timestamp": 1581944109860
}
]
}
]
}
}
我要实现的目标是从$lookup
获取所有值,并从 text 字段, first_name 字段和 last_name 字段获取搜索字符串如何做到这一点
What I want to achieve get all the value from $lookup
and the search string from text field, first_name field and last_name field how to achieve this
推荐答案
查询中出现语法错误,请尝试如下所示:
You've syntax error in query, Try as like given below :
var query = req.params.query;
const messages = await Message.aggregate([
{
$lookup: {
from: 'users',
localField: 'reference_id',
foreignField: '_id',
as: 'users'
}
}, { $match: { 'text': { '$regex': `.*${query}.*` } } }
])
问题是当您收到此错误时:参数必须是聚合管道运算符,如您所见,某些阶段或运算符正在聚合,例如 Ex:- $lookup
,$match
,$project
等.因此,如果聚合发现其他任何东西,它将引发错误.由于需要过滤数据,因此需要在$match
中包装代码'text': { '$regex':
. $ {query}. }
.
So the issue is when you get this error : Arguments must be aggregate pipeline operators, As you can see there are certain stages or operators in aggregation like Ex:- $lookup
, $match
, $project
etc.. so if aggregate finds anything other it would throw an error. Since you need to filter data you need to wrap you piece of code 'text': { '$regex':
.${query}.}
in $match
.
引用:聚合管道
这篇关于如何在mongodb中使用$ lookup和$ regex搜索的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!