【问题标题】:Filtered multiple returned docs in mongoDB在 mongoDB 中过滤多个返回的文档
【发布时间】:2014-09-11 19:30:41
【问题描述】:

我正在尝试执行每次返回文档的查询。问题是某些文档在数据库中有多个实例。因此,我没有得到一个带有查询的文档,而是得到了多个结果。因此,我尝试使用返回第一个查询匹配的 find_one 方法。但是,从 find 更改为 find_one 方法我面临一个新问题。我的代码如下:

lines = [line.rstrip() for line in open('ids.txt')]

list_names = []
names= open('name.txt', 'w')
for x in range(0,3000):
  id = int(lines[x])
  print x ,'  ',lines[x]
  for cursor in collection.find_one({"_id.uid": id}):
      name = cursor['screenname']
      print name
      list_names.append(name)
  names.write("%s\n" % name)
names.close()

我有一个 id 列表,我想从 mongoDb 返回对应的名称。但是,我得到 `name = cursor['screenname'] TypeError: 字符串索引必须是整数

我在这里做错了什么?

【问题讨论】:

  • 似乎变量 cursor 是字符串,我建议尝试 name = cursor[0] 或 name = cursor,或者在代码 pdb.set_trace() 的问题行之前添加以查看实际 cursor 是什么和如何处理
  • 为什么在 find() 的情况下它工作正常??

标签: python mongodb twitter tweepy


【解决方案1】:

find_one 方法不返回游标。它返回文档本身。

session = self.sessions.find_one({'_id': session_id})
print session # must print your document

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-07-23
    • 1970-01-01
    • 2022-06-30
    • 1970-01-01
    • 1970-01-01
    • 2015-08-26
    • 2016-01-21
    • 1970-01-01
    相关资源
    最近更新 更多