0

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']

1 Answer 1

1

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']
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.