简体   繁体   中英

How to query a string field contains one of array items?

I have documents like this:

{
name: '...'
}

I want to query for documents which names contains one of:

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

Of course it's easy to check for exact match like this:

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

I want use $regex with each item of cities. How to do that?

I also have tried:

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

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

Maybe there is a better way. Sample

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

Customize by yourself.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM