Bruno SENELLART
Bruno SENELLART

Reputation: 163

Using an expression $eq in an $cond mongoDB

I am trying to return "O" when the value of the field size.value is true and "N" when it's false. I am going for the $cond but so far it only return "O" because if I only put the path $size.value as a condition. Then the condition will be consider true if the field exist.

I tried to put an $eq on the value of $size.value but it's returning an error

db.getCollection('collectionA').aggregate(
   [
      {
         $project:
           {
             "Object":
               { $cond: { if: {"$size.value"{$eq:"true"}}, then: "O", else: "N" } },
           }
      }
   ]
)

Do we've any solution with this method or should I move and go with switch or any other method ?

Update : The value of the field '$size.value' is not a type boolean but a type String with 2 values possible 'true' and 'false'

So I am looking to check if the value of the field '$size.value' is a String equal to 'true' or 'false'

Upvotes: 2

Views: 5555

Answers (1)

whoami - fakeFaceTrueSoul
whoami - fakeFaceTrueSoul

Reputation: 17915

Please try below :

If you wanted to check value of field size.value is equal to true (this query would usually return 'N' on documents where size.value field doesn't exist or value of it doesn't match with true, Basically there is syntax error in your query) :

db.getCollection('yourCollectionName').aggregate(
    [
        {
            $project:
            {
                'Object':
                    { $cond: [{ $eq: ['$size.value', true] }, 'O', 'N'] }
            }
        }
    ]
)

Else if you wanted to check field size.value exists, then this (As $exist doesn't work with $cond we need to do this) :

db.getCollection('yourCollectionName').aggregate(
    [
        {
            $project:
            {
                'Object':
                    { $cond: [{ $ne: [{ $ifNull: ['$size.value', 'N'] }, 'N'] }, 'O', 'N'] }
            }
        }
    ]
)

Upvotes: 3

Related Questions