0

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

user2402616
  • 1,434
  • 4
  • 22
  • 38
  • 1
    what is foo? a driver variable(for example a javascript variable)? or a value that must be calculated in the database?(for example a mongodb field or variable `$$var`) – Takis Oct 01 '21 at 17:09
  • Apologies for unclarity. `foo` was supposed to represent just a generic boolean for the `$cond`. But I updated the post. The boolean itself is for if a specific field exists – user2402616 Oct 01 '21 at 17:18

2 Answers2

2

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"
            ]
          }
        ]
      }
    }
  }
])
Takis
  • 8,314
  • 2
  • 14
  • 25
0

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

Wernfried Domscheit
  • 54,457
  • 9
  • 76
  • 110