Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

MongoDB aggregate $match stage with conditional query

I want to do a match stage in mongoDB aggregate, and in this match I want to check if a condition exists, use a custom query, and if not, use another custom query. The custom queries are nested fields.

after searching and reading documents , I write this code. But it has an error.

I use MongoDB v4.4 . only this version and cannot switch to other versions.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

MongoError: FieldPath field names may not contain ‘.’.

{
  $match : {
    $expr : {
      $cond : {
        if: { $eq : [ 'type' , 'country'] },
        then: { 
          $and : [
            { 'countryState.status' : 'Confirmed' },
            { 'countryState.prop' : 'high' },          
          ]
        },
        else: {  },
      }
    }
  }
},

If the ‘type’ field, is equal to country, I want to use the custom query, and if not, only {} query.

I would appreciate anyone can help me, how to this match stage with conditional query.

>Solution :

You are asking for the query to return "this or that", so we should use $or. Borrowing the sample data from @cmgchess playground link, this query should logically do what you want I believe:

db.collection.aggregate([
  {
    $match: {
      $or: [
        {
          "type": "country",
          "countryState.status": "Confirmed",
          "countryState.prop": "high"
        },
        {
          "type": {
            $ne: "country"
          }
        }
      ]
    }
  }
])

Demo

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading