【问题标题】:python mongodb find method not workingpython mongodb查找方法不起作用
【发布时间】:2018-05-15 14:40:19
【问题描述】:

这是我的方法:

def mongo_find(collection_name, find_value):    
    list(MongoClient("localhost:27017").db[collection_name].find(find_value))


find_value = {'milestones.content': {'$regex': 'The idea'}}, {'milestones.content'}

print(list(mongo_find(collection_name, find_value)))

我收到此错误:

TypeError: filter must be an instance of dict, bson.son.SON, or other type that inherits from collections.Mapping

但以下工作正常:

list(MongoClient("localhost:27017").db[collection_name].find({'milestones.content': {'$regex': 'The idea'}}, {'milestones.content'}))

所以在运行mongo_find 方法时我尝试打印:

print(find_value)
({'milestones.content': {'$regex': 'The idea'}}, {'milestones.content'})

可能是因为两端都加了圆括号。有解决办法吗?

【问题讨论】:

  • 我不是蟒蛇人。不应该是项目 {'milestones.content':1}
  • 嗨!是的,它将按升序排列。在我这样做的方式中,它会在没有对齐的情况下打印出来。谢谢
  • 为什么 $regex 中没有模式我只看到纯文本。
  • 在上面的代码中,“db”代表什么。你能试试 list(MongoClient("localhost:27017")[].collection_name.find({'milestones.content': {'$regex': 'The idea'}}, {'milestones.content'} ))

标签: python-3.x mongodb arguments


【解决方案1】:

在您的工作示例中

list(MongoClient("localhost:27017").db[collection_name].find({'milestones.content': {'$regex': 'The idea'}}, {'milestones.content'}))

您实际上是在向 find 函数传递 两个 参数。第一个是dictionary 类型并指定一个过滤器

{'milestones.content': {'$regex': 'The idea'}}

而第二个是 python set,将用于投影

{'milestones.content'}

您的非工作版本将 one 参数传递给 find() 方法,该方法是一个 python tuple (输出中的圆括号来自哪里),看起来像这样:

({'milestones.content': {'$regex': 'The idea'}}, {'milestones.content'})

因此,要解决这个问题,您需要像在工作示例中那样传递两个参数:

def mongo_find(collection_name, filter. projection):
    list(MongoClient("localhost:27017").db[collection_name].find(filter, projection))

filter = {'milestones.content': {'$regex': 'The idea'}}
projection = {'milestones.content'}

print(list(mongo_find(collection_name, filter, projection)))

【讨论】:

  • 非常感谢
猜你喜欢
  • 2014-09-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-21
  • 2019-12-05
  • 2021-03-15
相关资源
最近更新 更多