【问题标题】:How to query a string field contains one of array items?如何查询一个字符串字段包含一个数组项?
【发布时间】:2018-02-12 06:47:30
【问题描述】:

我有这样的文件:

{
name: '...'
}

我想查询名称包含以下之一的文档:

cities = ['a', 'b', 'c']

当然,像这样检查完全匹配很容易:

col_areas = db['areas']
col_areas.find({'name': {'$in': cities}}) 

我想对每个城市项目使用$regex。该怎么做?

我也试过了:

for c in cities:
    cities_query.append('/^%s/' % c)

results = col_areas.find({'name': {'$in': cities_query}})

【问题讨论】:

标签: python mongodb mongodb-query


【解决方案1】:

也许有更好的方法。 样本

db.col_areas.aggregate([
    {
        $project: {
            'name': 1
        }
    },
    {
        $match: {
            $or:
                [{ 'name': { $regex: 'a', $options: 'g' } }]
        }
    }
])

自己定制。

【讨论】:

  • 你的意思是我必须像这样重复我的每个数组项?
  • 是的!并根据 [{ 'name': { $regex: 'a', $options: 'g' } }] 更改格式
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-06
  • 2020-12-22
  • 2012-09-19
  • 1970-01-01
  • 2013-03-13
  • 2012-11-21
相关资源
最近更新 更多