MongoDB在聚合查询中使用$ text [英] Mongodb using $text in aggregate query

查看:861
本文介绍了MongoDB在聚合查询中使用$ text的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用聚合搜索文本,我有以下代码.这是我的聚合查询,但不起作用.我希望先搜索文本,然后查找其中带有该词的帖子以找到用户,然后再按user.name和主题进行查询.

I'm trying to search in text with aggregate and I have the following code.Here is my aggregate query, but doesn't work. I expect to search first for the text and if find posts with that words in it to find user and then to query by user.name and the topic.

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,
        },
      },
    ]);

推荐答案

您可以从 match 查询中删除对象"text" ,然后将在匹配查询中直接输入$ text运算符,如下所示:

You can remove the object "text" from the match query and put the $text operator straight away within the match query as follows:

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

在执行上述操作之前,请确保已为要文本搜索的字段设置了索引类型作为文本.

Before executing the above make sure that you had made the index type as text for the field that you want to text search for.

就我而言,我已将 agent_id 字段标记为 文本IndexType .

In my case I had marked agent_id field as text IndexType.

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

Query Result: From the query you could see that I had simply entered faizul in the text search and not the full email address. Which works fine.

这篇关于MongoDB在聚合查询中使用$ text的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆