Home > OS >  How to extract value from MongoDB document in pymongo
How to extract value from MongoDB document in pymongo

Time:10-11

I'm new in MongoDB and I can't figure out how to extract values from mongo documents returned by queries.

Im trying to get the values of array called assigned_users:

building = await building_collection.find_one({"_id": ObjectId(building_id)}, {"assigned_users"})
print(building)

what I'm getting is:

{'_id': ObjectId('63431931d94475c22475925c'), 'assigned_users': ['6343191ed94475c22475925b', '6343191ed94475c22475925b', '6343191ed94475c22475925b', '6343191ed94475c22475925b', '6343191ed94475c22475925b', '6343191ed94475c22475925b', '6343191ed94475c22475925b', '63430c7e8c798a9778f28205', '63430c7e8c798a9778f28205']}

what I want to achieve is getting just a list:

['6343191ed94475c22475925b', '6343191ed94475c22475925b', '6343191ed94475c22475925b', '6343191ed94475c22475925b', '6343191ed94475c22475925b', '6343191ed94475c22475925b', '6343191ed94475c22475925b', '63430c7e8c798a9778f28205', '63430c7e8c798a9778f28205']

CodePudding user response:

When you are getting the data, you can filter the return data. In this case, you filtered assigned_users. However, '_id' is included by default. You can stop it by setting _id to False in the filter (optional)

building = await building_collection.find_one({"_id": ObjectId(building_id)}, {"_id": False, "assigned_users": True})

This will still return a dict.

{'assigned_users': ['6343191ed94475c22475925b', '6343191ed94475c22475925b', '6343191ed94475c22475925b', '6343191ed94475c22475925b', '6343191ed94475c22475925b', '6343191ed94475c22475925b', '6343191ed94475c22475925b', '63430c7e8c798a9778f28205', '63430c7e8c798a9778f28205']}

You can take the data out by

user = building['assigned_users']
  • Related