WhatCanWeDo
WhatCanWeDo

Reputation: 1

Checking for the existence of objects with certain fields in pymongo

I need to check if an object exists in the database that has at least one matching field with a field from the dictionary Pymongo

I have this, but it doesn't work:

import pymongo

client = pymongo.MongoClient()
users_db = client['UsersDB']
users_collection = users_db['users']

def check(collection, elements):
    return bool(collection.find_one(filter={'$or' : [item for item in elements.items()]}))

Upvotes: 0

Views: 93

Answers (1)

D. SM
D. SM

Reputation: 14490

You are on the right track but the query needs to be valid MQL. Try:

collection.find_one(filter={'$or' : [{k:{'$eq':v}} for k,v in elements.items()]})

Upvotes: 2

Related Questions