Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pymongo: How to check if field exists

I am using PyMongo to fetch documents from my collection. All was working fine, until I tried limit the results to only fetch documents where a specific field exists if a certain collection is selected. Here is my code

query["is_approved"] = None
if source_collection == "collection-name":
    query["field_to_check_for"]['exists'] = True


sort = [("created_date", -1)]
cursor = c.find(query, sort=sort).limit(20)

The above code throws a 400 'bad request' error on the line with

query["field_to_check_for"]['exists'] = True

I have also tried using

query["field_to_check_for"] = "exists"

but that returns an empty result

like image 738
Jez D Avatar asked Dec 13 '22 15:12

Jez D


1 Answers

your query dict is in wrong format, please try this one:

query = {"field_to_check_for": {"$exists": True}}
cursor = db.collection-name.find(query)  
like image 193
Xiaohong Yuan Avatar answered Jan 01 '23 01:01

Xiaohong Yuan