Search code examples
pythonpymongo

How to select some field in MongoDB using Pymongo?


Currently I have a devices table with the following properties: enter image description here

And i want to select userId, token, type field in this case with this code:

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
}

But it haven't any response:

{"data": []}

Solution

  • Problem

    You forgot the query parameter in your find() You have just put the filter parameter.

    Change in your code:

    To find in all documents:

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

    To find in a specific document:

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

    MongoDB find() specifying filter