问题
var query = req.params.query;
const messages = await Message.aggregate([
{
$lookup: {
from: 'users',
localField: 'reference_id',
foreignField: '_id',
as: 'users'
}
},
{'text': {'$regex': `.*${query}.*`}}
])
$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
}
]
}
]
}
}
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
回答1:
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}.*` } } }
])
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
.
Ref : aggregation-pipeline
来源:https://stackoverflow.com/questions/60314196/how-to-work-with-lookup-and-regex-search-in-mongodb