在 MongoDB 中,可以使用正则表达式进行匹配,并使用 $regex 操作符来实现。当匹配成功后,可以使用 $project 操作符来选择需要返回的字段。如果需要返回匹配到的数组元素,可以使用 $elemMatch 操作符或 $filter 操作符来实现。\n\n以下是一个示例:\njs\ndb.collection.aggregate([\n {\n \$match: {\n fieldName: {\n \$regex: /pattern/\n }\n }\n },\n {\n \$project: {\n matchedArray: {\n \$filter: {\n input: "\$arrayField",\n cond: {\n \$regexMatch: {\n input: "\$\$this",\n regex: /pattern/\n }\n }\n }\n }\n }\n }\n])\n\n\n在上述示例中,假设有一个集合(collection)包含字段(fieldName)和数组字段(arrayField)。我们使用 $match 操作符进行正则匹配,然后使用 $project 操作符选择需要返回的字段。在 $project 操作符中,我们使用 $filter 操作符来过滤数组字段,只返回匹配到的元素。在 $filter 操作符中,我们使用 $regexMatch 操作符进行正则匹配。\n\n请注意,上述示例中使用的是正则表达式 /pattern/,你需要将其替换为实际的正则表达式。

MongoDB 正则匹配数组元素:$regex & $filter 操作符 - 完整指南

原文地址: https://www.cveoy.top/t/topic/p7wM 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录