MongoDB 聚合多个部分匹配

MongoDB aggregation multiple partial matches

我正在将分页/过滤从客户端移到服务器上。

数据显示在 table 中,每列 header 都有一个文本输入框,您可以在其中输入内容并根据输入的内容过滤数据集。这对输入的内容使用简单的 indexOf 检查允许部分匹配的文本和数据集。

Example table column

    { name: "test 1" }, { name: "test 2" }

上面的图像/数据显示了 table 中的一列。如果我输入“tes”,两个结果都会出现。

    let filteredResults = data.filter(row => row.name.toLowerCase().indexOf(filterValue) > -1)

我现在已将此过滤移到服务器上,但我正在努力弄清楚如何在查询数据时进行类似的部分匹配。以下是我的查询:

    aggregate([
                {
                    $facet: {
                        results: [
                            {
                                $match: {
                                    "name": req.body.name
                                }
                            },
                            {
                                $skip: pageOptions?.pageNo ? (pageOptions.pageNo - 1) * 10 : 0
                            },
                            {
                                $limit: 10
                            }
                        ],
                        totalCount: [
                            {
                                $match: {
                                    "name": req.body.name
                                }
                            },
                            { $count: 'totalCount' }
                        ]
                    }
                },
                {
                    $addFields:
                    {
                        "total": { $arrayElemAt: ["$totalCount.totalCount", 0] }
                    }
                },
                {
                    $project: {
                        "totalCount": 0
                    }
                }
            ]

$match 阶段中的每个字段都是来自 table 的可能列,在本例中只是名称字段。您可以按大于 1 的条件进行过滤。以上内容适用于完全匹配,因此如果我们使用“test 1”搜索名称列,则会返回该记录,但如果我们搜索“tes”,则不会返回任何内容。

任何帮助都会很棒!

您可以使用 $regex 匹配来执行您的 case-insensitive,部分字符串匹配。

db.collection.aggregate([
  {
    $match: {
      "name": {
        // put your query in $regex option
        $regex: "tes",
        $options: "i"
      }
    }
  },
  {
    $facet: {
      results: [
        {
          $skip: 0
        },
        {
          $limit: 10
        }
      ],
      totalCount: [
        {
          $count: "totalCount"
        }
      ]
    }
  },
  {
    $addFields: {
      "total": {
        $arrayElemAt: [
          "$totalCount.totalCount",
          0
        ]
      }
    }
  },
  {
    $project: {
      "totalCount": 0
    }
  }
])

这里是Mongo playground供大家参考。

我能够通过使用文本索引和 $text 运算符解决这个问题:

[
            {
                $match: { $text: { $search: "asdfadsf" } }
            }
]