Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

{"data": []}

>Solution :

Problem

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

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading