如何使用PyMongo在MongoDB中指定字段查询?返回空结果求助
解决MongoDB查询返回空数组的问题
问题场景
我有一个devices集合,字段包含userId、token、type、deviceId、_id等。想要查询集合中所有文档的userId、token、type字段,编写了如下代码,但执行后返回{"data": []},没有获取到有效数据。
原代码
client = pymongo.MongoClient('mongodb://this is my connection') # Set database db = client.test devices = db.devices cursor = devices.find({"userId": 1, "token": 1, "type": 1, "deviceId": 0, "_id" : 0}) result = [] for document in cursor: result.append(document) print(result) return { "data": result }
执行结果
{"data": []}
问题原因
pymongo的find()方法参数使用错误:
- 第一个参数是过滤条件,用于筛选符合条件的文档
- 第二个参数才是投影规则,用于指定返回哪些字段
你把投影规则写在了第一个参数位置,相当于让MongoDB查找userId等于1、token等于1、type等于1的文档,而你的集合中没有符合该条件的文档,所以返回空数组。
解决方案
将投影参数移到find()的第二个参数位置,第一个参数留空(表示查询所有文档):
修正后的代码
client = pymongo.MongoClient('mongodb://this is my connection') # Set database db = client.test devices = db.devices # 第一个参数为空表示查询所有文档,第二个参数指定返回的字段 cursor = devices.find({}, {"userId": 1, "token": 1, "type": 1, "deviceId": 0, "_id" : 0}) result = [] for document in cursor: result.append(document) print(result) return { "data": result }
代码优化
可以直接将游标转换为列表,简化循环逻辑:
client = pymongo.MongoClient('mongodb://this is my connection') db = client.test devices = db.devices cursor = devices.find({}, {"userId": 1, "token": 1, "type": 1, "deviceId": 0, "_id" : 0}) # 直接将游标转为列表 result = list(cursor) print(result) return { "data": result }
内容的提问来源于stack exchange,提问作者TranDatK
相关产品推荐
相关产品推荐

