Check for multiple fields in a MongoDB document

I am trying to query a database collection that contains process documents for those documents that have certain fields. For simplicity, imagine the following general outline of a document:

{
    "timestamp": ISODate("..."),
    "result1": "pass",
    "result2": "fail"
}

Now, when the process starts, a new document is inserted only with a time stamp. When this process reaches a certain stage, the field result1and result2added to over time. However, some processes do not reach stages 1or 2, therefore, do not have result fields.

I would like to query the database to retrieve only those documents that have BOTH result1and result2.

I know about $ exists , but as far as I can tell, this only works for one field at a time, i.e. db.coll.find({"result1": {$exists: true}}). An operator $existscannot be used as a top-level operator. For instance. this does not work :

db.coll.find({"$exists": {"result1": true, "result2": true}})

To check both results, I will need:

db.coll.find({"result1": {"$exists": true}, "result2": {"$exists": true}})

Now this is already tiring for several variables.

Is there a better way to do this? (Also, I am doing this in Python, so if there is a solution only for the pymongo driver that will make me happy.)

+4
source share
2 answers

I do not know which is better, but you can always handle JavaScript through : $where

jsStr = """var doc = this;
           return ['result1','result2','result3']
           .every(function(key) { 
               return doc.hasOwnProperty(key) 
           });"""

coll.find({ "$where": jsStr })

But you will need to specify an array of "keys" to check somewhere.

, , "" :

whitelist = [ "result1", "result2", "result3" ]
query = {}

for key in whitelist:
    query[key] = { "$exists": True }

coll.find(query)

, MongoDB - , .

+2

$and:

db.coll.find({"$and": [                                                                     
            { "fld1": { "$exists": true }}                                              
            , { "fld2": { "$exists": true }}                                            
            , { "fld3": { "$exists": true }}                                            
]})  
+1

All Articles