【问题标题】:mongodb: query to check if item in an array contains a particular string [duplicate]mongodb:查询以检查数组中的项目是否包含特定字符串[重复]
【发布时间】:2018-11-03 20:17:36
【问题描述】:

我有一个名为 products 的集合,其中包含以下项目

[
  { 
    name: 'Product 1'
    images: ['http://staging.example.com/1', 'http://production.example.com/2'],
    ... 
  },
  { 
    name: 'Product 2'
    images: ['http://production.example.com/3'],
    ... 
  }
]

我想在images 数组中查找包含字符串staging 的文档。

我尝试了一些方法,例如使用 $contains,但 mongo 抛出错误说我不能将 $contains 与数组一起使用。

【问题讨论】:

    标签: arrays mongodb


    【解决方案1】:

    我认为您可能需要在这里进行正则表达式搜索。

    试试:

    db.collection.find({images: /staging/});
    

    【讨论】:

    • 啊!可能已经猜到了:) 谢谢!
    • 不客气~
    • 您是否也知道如何使用更新将staging 更新为productiondb.collection.update({images: /staging/}, { $set: { 'images.$[]': ? } })
    • staging 是您的字符串值的一部分。我认为更新部分字符串不在 mongo 之手
    【解决方案2】:
    db.products.find({images: /staging/i});
    

    我认为这会有所帮助

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-08-15
      • 1970-01-01
      • 1970-01-01
      • 2010-11-16
      • 2013-01-12
      • 1970-01-01
      • 2013-10-27
      • 2015-06-24
      相关资源
      最近更新 更多