Mongodb using $text in aggregate query

大城市里の小女人 提交于 2020-06-29 03:38:13

问题


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

回答1:


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.

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

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.




回答2:


$text is an expression-level operator, not a field-level operator. See the documentation for correct usage.

There can only be one text index defined on a collection and this index is used by the $text operator, therefore it is redundant to specify the field name(s) with $text.



来源:https://stackoverflow.com/questions/62616465/mongodb-using-text-in-aggregate-query

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!