如何使用 Pymongo 选择 MongoDB 中的某些字段?

问题描述 投票:0回答:2

目前我有一个具有以下属性的设备表:

我想在这种情况下使用以下代码选择 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": []}
python pymongo
2个回答
1
投票

您错误地使用了 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
}

0
投票

我认为忘记了 find() 中的查询 您刚刚安装了过滤器。

在所有文档中查找:

cursor = devices.find({}, {"userId": 1, "token": 1, "type": 1, "deviceId": 0, "_id" : 0})

MongoDB find() 指定过滤器

© www.soinside.com 2019 - 2024. All rights reserved.