【问题标题】:how to work with $lookup and $regex search in mongodb如何在 mongodb 中使用 $lookup 和 $regex 搜索
【发布时间】:2020-06-04 10:33:27
【问题描述】:
  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 我有数据之后,参数必须是聚合管道运算符

{
    "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 字段中获取搜索字符串如何做到这一点

【问题讨论】:

    标签: mongodb mongodb-query aggregation-framework


    【解决方案1】:

    您在查询中有语法错误,请尝试如下所示:

    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 等.. 所以如果聚合发现任何其他内容,它将引发错误。由于您需要过滤数据,因此您需要将一段代码 'text': { '$regex':.${query}.} 包装在 $match 中。

    参考: aggregation-pipeline

    【讨论】:

    • 谢谢,我试过这种方式,你能检查一下我的回答,这有什么问题吗?
    • 当试图用名字和姓氏搜索它时,为什么会返回空白?
    • @Shivam :这是因为 users 数组是在 $lookup 阶段之后创建的,但是如果您在 $match 之前使用 user.first_name $lookup 查询将无法找到任何名为users 的字段。所以它只能在text字段上工作,但如果你最后使用$match,你可以查询所有3个字段..
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-05-02
    • 2019-05-23
    • 2021-09-21
    • 1970-01-01
    • 2018-02-06
    • 2013-07-31
    • 1970-01-01
    相关资源
    最近更新 更多