【问题标题】:Mongodb using $text in aggregate queryMongodb 在聚合查询中使用 $text
【发布时间】:2020-10-18 08:06:19
【问题描述】:

我正在尝试使用聚合搜索文本,我有以下代码。这是我的聚合查询,但不起作用。我希望首先搜索文本,如果找到包含该词的帖子以查找用户,然后通过 user.name 和主题进行查询。

const posts = await Post.aggregate([
      {
        $match: {
          $text: {
            $search: postWords ? `${postWords}` : /.*/,
            $caseSensitive: false,
          },
        },
      },
      {
        $lookup: {
          from: "users",
          localField: "user",
          foreignField: "_id",
          as: "user",
        },
      },
      {
        $unwind: "$user",
      },
      {
        $match: {
          $and: [
            {
              topic: {
                $regex: postTopic ? postTopic : /.*/,
                $options: "i",
                $exists: true,
              },
            },
            {
              "user.name": {
                $regex: postName ? postName : /.*/,
                $options: "i",
                $exists: true,
              },
            },
            { text: { $regex: postWords ? postWords : /.*/, $options: "i" } },
          ],
        },
      },
      {
        $skip: req.params.page ? (req.params.page - 1) * 10 : 0,
      },
      {
        $limit: 11,
      },
      {
        $project: {
          "user.password": 0,
          "user.active": 0,
          "user.email": 0,
          "user.temporaryToken": 0,
        },
      },
    ]);

【问题讨论】:

    标签: mongodb mongoose mongodb-query aggregation-framework


    【解决方案1】:

    $text 是表达式级别的运算符,而不是字段级别的运算符。请参阅documentation 了解正确用法。

    在一个集合上只能定义一个文本索引,并且该索引由 $text 运算符使用,因此用 $text 指定字段名称是多余的。

    【讨论】:

    • 任何想法如何通过单词数组或其他东西在字符串中搜索?如果有任何匹配项也可以返回。
    • 我相信将单词加入带有空格的字符串是可行的。
    • Atlas 提供摘录:docs.atlas.mongodb.com/reference/atlas-search/highlighting/…。非 Atlas 部署不会。
    • 你能给我一个例子我应该如何实现这个,因为我尝试了任何东西,但仍然是 0 进度,谢谢!
    • 如何实现什么?
    【解决方案2】:

    您可以从 ma​​tch 查询中删除对象 "text" 并将 $text 运算符 直接放入 match 查询中,如下所示:

    db.notifications.aggregate([
        {
            $match: {
                $text: {
                    $search: "faizul"
                }
            }
        }
    ])
    

    在执行上述操作之前,请确保您已将 index type 设置为 text 用于您要进行文本搜索的 field

    就我而言,我已将 agent_id 字段标记为 text IndexType

    查询结果: 从查询中您可以看到我只是在文本搜索中输入了 faizul 而不是完整的电子邮件地址。效果很好。

    【讨论】:

    • postWords 是用空格分隔的数组或字符串,如果我尝试这样做,让我们说“asd dsa”并且有一个文本与完全相同的单词有效,但如果我尝试转身“ dsa asd" 不起作用,还要编辑我的聚合,以便您看到它
    猜你喜欢
    • 2019-06-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-13
    • 1970-01-01
    • 2021-09-27
    相关资源
    最近更新 更多