【问题标题】:How to search value in two or more different fields in MongoDB如何在 MongoDB 中的两个或多个不同字段中搜索值
【发布时间】:2020-06-11 15:46:57
【问题描述】:

我的节点模型在用户集合中包含以下字段:

firstName: {
   type: String,
},
lastName: {
   type: String
},
mobile: {
   type: String,
   unique: true
},
email: {
   type: String,
   index: true,
   unique: true
}

现在假设我收集了以下记录:

现在,当我使用以下条件搜索记录时,它没有返回任何内容:

"$or": [
{
  "firstName": {
    "$regex": "Sunil Narine",
    "$options": "i"
  }
},
{
  "lastName": {
    "$regex": "Sunil Narine",
    "$options": "i"
  }
},
{
  "email": {
    "$regex": "Sunil Narine",
    "$options": "i"
  }
},
{
  "mobile": {
    "$regex": "Sunil Narine"
  }
}

]

如果我只传递Sunil 或Narine,那么它会返回结果,但是当我传递firstName 和lastName 的组合值时,即Sunil Narine,它不会返回结果。

我也尝试了以下不同的方法,但没有任何效果:

"$regex": /^Sunil Narine$/,
"$options": "i"
OR
"$regex": /$Sunil Narine.*/,
"$options": "i"
OR
"$regex": /^Sunil Narine/,
"$options": "i"

所以任何人都有解决这个问题的想法。 非常感谢您的帮助。

【问题讨论】:

  • 你考虑过使用text search吗?
  • 不,@Joe,这对我没有帮助。

标签: node.js mongodb mongoose mongodb-query


【解决方案1】:

从您的问题看来,如果它包含 Sunil 或 Narain,您似乎想要得到结果。

此正则表达式将匹配 Sunil 或 Narine。

"$regex": /(Sunil)|(Narine)/g

【讨论】:

  • 感谢易卜拉欣的回复。因此,根据您的回答,我需要用管道| 替换空间,对吗?因为Sunil Narine 只是一个例子,实际上应该有任何值
猜你喜欢
  • 2012-02-06
  • 1970-01-01
  • 2013-03-21
  • 2017-06-26
  • 1970-01-01
  • 2022-01-25
  • 2013-03-07
  • 1970-01-01
  • 2022-01-20
相关资源
最近更新 更多