Search code examples
python-3.xmongodbpymongo-3.x

MongoDB query to return empty result when an array element does not match


I have a MongoDB document like below, I would like to query values.mark greater than 50 and available=true and return documents when the values.available=true. If anyone of the value has available=False the whole document should not be returned.

{
  "_id": 1,
  "values": [
    {
      "mark": 30,
      "available": true
    },
    {
      "mark": 80,
      "available": false
    },
    {
      "mark": 65,
      "available": true
    }
  ]
}

Query:

{"values.mark": {"$gt":50}, 'values.available': true}

The result for the query

{
  "_id": 1,
  "values": [
    {
      "mark": 30,
      "available": true
    },
    {
      "mark": 80,
      "available": false
    },
    {
      "mark": 65,
      "available": true
    }
  ]
}

In the above case, one of the value for available is False so it should not return the document instead it should be empty. Can someone help me how to achieve the expected result?


Solution

  • Maybe something like this:

      db.collection.find({
        "values.mark": {
        $gt: 50
       },
        $nor: [
        {
          "values": {
            $elemMatch: {
              "available": {
                $nin: [
                  true
                ]
              }
            }
          }
        }
      ]
    })
    

    playground