24

I want to find a document using a conditional if the key == None or if the key doesn't exist. Something like this:

myDoc = self.request.root.db.myDocs.find_one({
                          '$or': [
                              {'myKey' : $doesNotExist } ,
                              {'myKey' : None }
                            ]
                    })

I'd also like to be able to find a document just by a missing key like this:

myDoc = self.request.root.db.myDocs.find_one( {'myKey' : $doesNotExist } )

How can I accomplish this?

zakdances
  • 22,285
  • 32
  • 102
  • 173

2 Answers2

29

For "if key exists" checks, using a .find() is significantly faster than find_one().

Single document: cursor = db.myDocs.find({"mykey": {"$exists": True}}).limit(1)

Multiple documents: cursor = db.myDocs.find({"mykey": {"$exists": True}})

if cursor.count() > 0:
    keyExists = True
else:
    keyExists = False
Sagar Hatekar
  • 8,700
  • 14
  • 56
  • 72
19

You can test for a key not existing with:

db.myDocs.find_one({'myKey': { '$exists': False }})

Mongo documentation about the $exists operator

Etienne
  • 655
  • 3
  • 15
Joe Day
  • 6,965
  • 4
  • 25
  • 26
  • 1
    I'm using MongoDB compass (1.24.6), and "False" didn't work but this worked: `{"myKey": {$exists: 0}}` – MD004 Mar 16 '22 at 23:02