【问题标题】:Pymongo Regex $all multiple search termsPymongo Regex $all 多个搜索词
【发布时间】:2014-09-27 08:58:28
【问题描述】:

我想搜索 MongoDB,以便只获得在某个配置中同时在键中找到所有 x 的结果。

collected_x =  ''
for x in input:
  collected_x = collected_x + 're.compile("' + x + '"), '
  collected_x_cut = collected_x[:-2]

cursor = db.collection.find({"key": {"$all": [collected_x_cut]}})

这并没有带来预期的结果。如果我自己输入多个x,它就可以了。

cursor = db.collection.find({"key": {"$all": [re.compile("Firstsomething"), 
                                              re.compile("Secondsomething"),
                                              re.compile("Thirdsomething"), 
                                              re.compile("Fourthsomething")]}})

我做错了什么?

【问题讨论】:

    标签: python regex mongodb pymongo


    【解决方案1】:

    您正在 for 循环中构建一个字符串,而不是 re.compile 对象的列表。你想要:

    collected_x = []                            # Initialize an empty list
    
    for x in input:                             # Iterate over input
      collected_x.append(re.compile(x))         # Append re.compile object to list
    
    collected_x_cut = collected_x[:-2]          # Slice the list outside the loop
    
    cursor = db.collection.find({"key": {"$all": collected_x_cut}})
    

    一种简单的方法是使用map 来构建列表:

    collected = map(re.compile, input)[:-2]
    db.collection.find({"key": {"$all": collected}})
    

    list comprehension

    collected = [re.compile(x) for x in input][:-2]
    db.collection.find({"key": {"$all": collected}})
    

    【讨论】:

      猜你喜欢
      • 2016-02-26
      • 1970-01-01
      • 1970-01-01
      • 2020-09-15
      • 2021-05-01
      • 2021-07-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多