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

2
  • 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) Commented Oct 1, 2021 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 Commented Oct 1, 2021 at 17:18

2 Answers 2

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"
            ]
          }
        ]
      }
    }
  }
])
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.