【问题标题】:Mongodb case insensitive $pull from arrayMongodb 不区分大小写 $pull from array
【发布时间】:2018-12-14 16:11:45
【问题描述】:

我有一个 mongodb 集合名称雇主,下面是一些示例文档

[{
"companyName" : "XYZ Corp",
"employee" : [
    {
        "name" : "john smith"
    },
    {
        "name" : "john doe"
    }
 ]
 },
 {
  "companyName" : "ABC Corp",
  "employee" : [
    {
        "name" : "Marco Doe"
    },
    {
        "name" : "Mark smith"
    }
  ]
  }]

现在我想编写一个不区分大小写的查询,我将提供 companyName 和员工姓名,并希望从员工数组中提取该员工姓名。 我写了一个类似的查询

db.employer.update({companyName: { '$regex': /^ABC Corp$/i }}, {$pull: {employee: {name: '/^mark smith$/i'}}})

考虑在任何情况下都将存储员工姓名。上面的查询不起作用,它没有从数组中提取相应的员工姓名mark smith

【问题讨论】:

    标签: node.js mongodb


    【解决方案1】:

    试试这个。 :)

    db.employer.update(
      {
        companyName: { 
          '$regex': /^ABC Corp$/i 
        }
      }, 
      {
        $pull: {
          employee: {
            name: {
              regex: '/^mark smith$/i'
            }
          }
        }
      }
    )
    

    【讨论】:

      【解决方案2】:

      考虑这个例子,

      { <field>: { $regex: /pattern/, $options: '<options>' } }
      

      您还可以阅读完整文档或查看更多 Mongodb 正则表达式示例here.

      我认为您不只是搜索{field: /regex/i},您需要分别指定使用正则表达式的每个字段。

      因此你的代码应该是,

      db.employer.update({companyName: { '$regex': /^ABC Corp$/i }}, {$pull: {employee: {name: {regex: /^mark smith$/i}}}})
      

      名称字段也会根据正则表达式进行搜索。

      因为您上面的代码仅在 companyName 字段上使用正则表达式,而不是名称字段。

      另外,请记住删除正则表达式模式中的引号。 cmets 的说明(谢谢,Johne)。

      【讨论】:

      • 修改后的查询将是 db.employer.update({companyName: { '$regex': /^ABC Corp$/i }}, {$pull: {employee: {name: {$regex : /^mark smith$/i}}}})
      • 当然,因为正则表达式模式中没有引号。谢谢@JohneDoe!
      猜你喜欢
      • 2019-01-31
      • 1970-01-01
      • 2014-05-20
      • 2015-10-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-01
      • 2013-03-06
      相关资源
      最近更新 更多