【问题标题】:PyMongo query not returning results although the same query returns results in mongoDB shellPyMongo 查询未返回结果,尽管相同的查询在 mongoDB shell 中返回结果
【发布时间】:2016-11-18 22:32:00
【问题描述】:
import pymongo
uri = 'mongodb://127.0.0.1:27017'
client = pymongo.MongoClient(uri)
db = client.TeamCity
students = db.students.find({})
for student in students:
    print (student)

Python 结果:

空白

MongoDB:结果

db.students.find({})

{ "_id" : ObjectId("5788483d0e5b9ea516d4b66c"), "name" : "Jose", "mark" : 99 }
{ "_id" : ObjectId("57884cb3f7edc1fd01c3511e"), "name" : "Jordan", "mark" : 100
}

import pymongo
uri = 'mongodb://127.0.0.1:27017'
client = pymongo.MongoClient(uri)
db = client.TeamCity
students = db.students.find({})
print (students.count())

Python 结果:

0

mongoDB 结果

db.students.find({}).count()

2

我错过了什么?

对于

import pymongo
uri = 'mongodb://127.0.0.1:27017'
client = pymongo.MongoClient(uri)
db = client.TeamCity
students = db.students.find({})
print (students)

Python 结果:

所以我认为它能够成功连接到数据库但没有返回结果

【问题讨论】:

  • 能否在 mongoDB shell 中显示你的数据库名称,即命令 'db' 的输出
  • > 显示 dbs Teamcity 0.000GB 本地 0.000GB

标签: python mongodb pymongo


【解决方案1】:

像这样尝试你的 pymongo 代码,即将 TeamCity 更改为 Teamcity

打印所有学生:

import pymongo
uri = 'mongodb://127.0.0.1:27017'
client = pymongo.MongoClient(uri)
db = client.Teamcity
students = db.students.find({})
for student in students:
    print (student)

统计所有学生:

import pymongo
uri = 'mongodb://127.0.0.1:27017'
client = pymongo.MongoClient(uri)
db = client.Teamcity
students = db.students.find({})
print (students.count())

【讨论】:

  • 非常感谢。当您要求显示我的 .database 的名称时,我想通了
【解决方案2】:

我知道这个问题很久以前就有答案了,但是我今天遇到了同样的问题,而且原因不一样,所以我在这里添加一个答案。

在 shell 上工作的代码:

> db.customers.find({"cust_id": 2345}, {"pending_questions": 1,  _id: 0})
{ "pending_questions" : [ 1, 5, 47, 89 ] }

代码在 PyMongo 中不起作用(通过网络表单设置 cust_id):

db.customers.find({"cust_id": cust_id}, {"pending_questions": 1,  "_id": 0})

事实证明,shell 中的数字被解释为整数,而 Python 代码中使用的数字被 PyMongo 解释为浮点数,因此不返回匹配项。这证明了这一点:

cust_id = int(request.args.get('cust_id'))
db.customers.find({"cust_id": cust_id}, {"pending_questions": 1,  "_id": 0})

产生结果: [1.0, 5.0, 47.0, 89.0]

简单的解决方案是在 python 代码中将所有内容类型转换为 int。总之,shell 推断的数据类型可能与 PyMongo 推断的数据类型不同,这可能是在 PyMongo 中运行时在 shell 上返回结果的查找查询不返回任何内容的原因之一。

【讨论】:

    猜你喜欢
    • 2019-09-18
    • 1970-01-01
    • 2014-05-05
    • 2020-01-11
    • 1970-01-01
    • 2012-07-26
    • 1970-01-01
    • 1970-01-01
    • 2013-10-01
    相关资源
    最近更新 更多