Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongo conditional for "key doesn't exist"?

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?

like image 846
zakdances Avatar asked Aug 19 '12 22:08

zakdances


2 Answers

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
like image 61
Sagar Hatekar Avatar answered Dec 07 '22 23:12

Sagar Hatekar


You can test for a key not existing with:

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

Mongo documentation about the $exists operator

like image 45
Joe Day Avatar answered Dec 08 '22 00:12

Joe Day