MongoDB - 从数组中返回所有正则表达式匹配

发布于 2025-01-12 05:57:02 字数 1316 浏览 0 评论 0原文

我有一个 mongoDB 文档,其中包含电子邮件地址列表。我想使用正则表达式返回单个文档中匹配电子邮件地址的数组。我不需要找到集合中的所有匹配项。我假设我需要使用聚合,但我无法让它正常工作。有什么建议吗?

{
    "_id": {
        "$oid": "621fbc842ff7d84973d537e7"
    },
    "name": "Test",
    "emailAddresses": ["[email protected]", "[email protected]", "[email protected]", "[email protected]"],
    "_class": "com.email.models.Group"
}

搜索“ema”,将返回:

{
    "emailAddresses": ["[email protected]", "[email protected]", "[email protected]" ]
}

I have a mongoDB document that contains a list of email address. I'd like to use a regEx expression to return an array of matching email address in the single document. I don't need to find all matches in the Collection. I'm assuming I need to use aggregation but I can't get it to work correctly. Any advice?

{
    "_id": {
        "$oid": "621fbc842ff7d84973d537e7"
    },
    "name": "Test",
    "emailAddresses": ["[email protected]", "[email protected]", "[email protected]", "[email protected]"],
    "_class": "com.email.models.Group"
}

Search for "ema", would return:

{
    "emailAddresses": ["[email protected]", "[email protected]", "[email protected]" ]
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

美羊羊 2025-01-19 05:57:02

像这样的东西:

 db.collection.aggregate([
  {
   $addFields: {
     emailAddresses: {
      $filter: {
       input: "$emailAddresses",
       cond: {
        "$regexMatch": {
          input: "$this",
          regex: "ema"
        }
       }
      }
     }
    }
   }
 ])

解释:

使用 $filter 定义 addFields 聚合阶段来替换原始 emailAddresses 数组,在过滤器的输入中提供 emailAddresses 数组和过滤器条件添加正则表达式,通过该正则表达式来过滤数组元素。

游乐场

Something like this:

 db.collection.aggregate([
  {
   $addFields: {
     emailAddresses: {
      $filter: {
       input: "$emailAddresses",
       cond: {
        "$regexMatch": {
          input: "$this",
          regex: "ema"
        }
       }
      }
     }
    }
   }
 ])

Explained:

Define addFields aggregation stage with $filter to replace the original emailAddresses array , in the input for the filter provide the emailAddresses array and condition for the filter add regex expression by which the array elements will be filtered.

playground

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文