Check the value of a key

Hi,

im working on a PyGame. My problem is, how to check if a user exists or not in my collection.
I mean, how can i check if a variable is equal to my key:value.
Something like this:

user: [
{
‘User’ : ‘Tim’
‘Password’:‘password’
}
]

if (‘user’:‘Tim’) is equal ‘Tim’:
return

thx

Hello @Senel_Ekiz, welcome to the MongoDB Community forum!

To access MongoDB database and the data stored in its collections, you can use the PyMongo driver software. The APIs of the driver allow you to connect to the database and query the data from your Python program.

You can use the collection.find_one method for checking the value of a key. For example:

result = collection.find_one( { 'user': 'Tim' } )

The value of the result will be None in case no match is found. In case a match is found the value of the result will be the document.

Here is the PyMongo tutorial for using the find_one:

https://pymongo.readthedocs.io/en/stable/tutorial.html#getting-a-single-document-with-find-one

2 Likes

Thx for you answer.

But, how can i check, if the only the value(‘Tim’) exists?

My Code:

def check_user():
    result = user.find_one({'User':'dsada'})
    if result == model.User.user_input:
        print("user exist")
    else:
        print("user dont exist")

My ‘user_input’ is the texfield in my Menue.

Additional:

i want to iterate over every collection in my Database, to check if any ‘User’ Key have a value from my Input.

I think you can use this:

# Assuming the field user_input has a value, for example, "Tim"
# And the field User represents the name of the user
result = user.find_one( { 'User': user_input } )

if result:
    print("user exists")
else:
    print("user not found")
1 Like

Perfect. Its work. Thank you.

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.