I've got the following problem. I don't seem to figure out on how to access the "UID" value within the warning field. I want to iterate over every value inside the document, and access every existing UID to check if a randomly generated UID already exists. I'm honestly about to have a mental breakdown due this, I just can't seem to figure it out
This is what my MongoDB structure looks like: https://i.sstatic.net/RmdMT.png
warnings will be a list after you've got the object in python code - so you can just iterate over the docs in the warnings
list and access their UID
keys
edited code for comments:
We can get all the documents in the collection by using find
with an empty query dict, though I've linked the docs on find below. As your document structure seems to have a random number as a key, and then an embedded doc, we find the keys in the document that aren't _id
. It may be that there's only one key, but I didn't want to assume. If there's then a warnings
key in our embedded doc, we iterate over each of the warnings and add the "UID" to our warning_uids
list.
# this is your collection object
mod_logs_collection = database["modlogs"]
all_mod_docs = mod_logs_collection.find({})
warning_uids = []
for doc in all_mod_docs:
# filter all the doc keys that aren't the default `_id`
doc_keys = [key for key in doc.keys() if key != "_id"]
# not sure if it's possible for you to have multiple keys in a doc
# with this structure but we'll iterate over the top-level doc keys
# just in case
for key in doc_keys:
sub_doc = doc[key]
if warnings := sub_doc.get("warnings")
for warning in warnings:
warning_uids.append(warning["UID"])
print(warning["UID"])