我想在这种情况下使用以下代码选择 userId、token、type 字段:
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": []}
您错误地使用了 find 方法。
import pymongo
# Connect to MongoDB
client = pymongo.MongoClient('mongodb://your_connection_string')
# Set database and collection
db = client.test
devices = db.devices
# Define a projection to select the desired fields
projection = {"userId": 1, "token": 1, "type": 1, "_id": 0}
# Use the projection in the find method
cursor = devices.find({"userId": 1}, projection)
# Initialize a list to store the results
result = []
# Iterate through the cursor and append documents to the result list
for document in cursor:
result.append(document)
print(result)
# Return the result
return {
"data": result
}
我认为忘记了 find() 中的查询 您刚刚安装了过滤器。
在所有文档中查找:
cursor = devices.find({}, {"userId": 1, "token": 1, "type": 1, "deviceId": 0, "_id" : 0})