Home > front end >  Mongo Aggregate Conditional query within $match
Mongo Aggregate Conditional query within $match

Time:10-02

Basically, if one field exists, I want to run a query, otherwise, I want to run a separate one.

`db.Collection.aggregate([
    {
        $match: {
            $cond: [{if fieldOnCollection:{$exists:true}}, {fieldOnCollection:'foo'}, {anotherField:'bar'}]
        }
    }
]);`

I've only ever seen $cond used in other stages and not to construct an actual part of the query consisting of fields on the collection itself

CodePudding user response:

Query1
(without aggregate operators)

Test code here

db.collection.aggregate({
  "$match": {
    "$or": [
      {
        "fieldOnCollection": "foo"
      },
      {
        "$and": [
          {
            "fieldOnCollection": {
              "$exists": false
            }
          },
          {
            "anotherField": "bar"
          }
        ]
      }
    ]
  }
})

Query2
(with aggregate operators similar to your query)

  • if field exists, test if its equal with "foo"
  • else check if the other field is equal with "bar"

Test code here

db.collection.aggregate([
  {
    "$match": {
      "$expr": {
        "$cond": [
          {
            "$ne": [
              {
                "$type": "$fieldOnCollection"
              },
              "missing"
            ]
          },
          {
            "$eq": [
              "$fieldOnCollection",
              "foo"
            ]
          },
          {
            "$eq": [
              "$anotherField",
              "bar"
            ]
          }
        ]
      }
    }
  }
])

CodePudding user response:

Not clear, what you try to achieve. Anyway, your syntax is wrong. It would be like this:

{ $cond: [
   { $ne : ["$fieldOnCollection", undefined] }, 
   'foo', 
   'bar'
   ]
}

or

{ $cond: {
   if: { $ne : ["$fieldOnCollection", undefined] }, 
   then: 'foo', 
   else: 'bar'
   }
}

If you need to check whether a field exists, see https://stackoverflow.com/a/68255564/3027266

  • Related